title author date CreateTime categories
WPF 自定义 TextBoxView 的 Margin 大小
lindexi
2018-09-28 17:16:17 +0800
2018-09-28 16:59:57 +0800
WPF

在 WPF 的 TextBox 里有 TextBoxView 用来渲染 TextBox 内容,但是在 TextBox 里面的 TextBoxView 是不能直接设置而且默认的 Margin 是 2,0,2,0 如何自定义这个值

先来写一个简单的程序告诉大家这个问题,创建一个空白 WPF 程序,在里面添加一个 TextBox 设置 TextBox 居中

        <TextBox Width="100" HorizontalAlignment="Center" VerticalAlignment="Center">

        </TextBox>

        <TextBlock Margin="10,100,10,10" Text="欢迎访问我博客 http://lindexi.gitee.io 里面有很多 UWP 博客" HorizontalAlignment="Center" VerticalAlignment="Center"></TextBlock>

可以看到现在的 TextBox 光标和 TextBox 的左边有 2 像素的距离,通过 Snoop 可以看到这个 TextBoxView 的 Margin 是 2,0,2,0 而且无法直接修改

从 WPF 的源代码可以看到 TextBoxView 是 internal 的也就是无法直接修改 Style 在构造函数设置了 Margin 的值,这里的 CaretElement.BidiCaretIndicatorWidth 就是 2 这就是默认的大小

最简单的解决方法是通过设置 TextBox 的 Padding 的方法

        <TextBox Width="100" Padding="-2,0,-2,0" HorizontalAlignment="Center" VerticalAlignment="Center">

        </TextBox>

因为在 TextBox 里面存在 TextBoxView 的偏移,使用相反的值可以让 TextBoxView 的偏移取消,这里的 Padding 需要根据自己的需要设置

如果设置 Padding 的负数比较小,如 -500 就可以在 TextBox 的外面输入

如果这里的 TextBox 不是在 ListView 或其他控件使用了 TextBox 的,可以使用自己创建的类继承 TextBox 可以通过在 Load 重写控件的 Margin 重写

    public class PeedereJiyay : TextBox
{
/// <inheritdoc />
public PeedereJiyay()
{
Loaded += PeedereJiyay_Loaded;
} private void PeedereJiyay_Loaded(object sender, RoutedEventArgs e)
{
if (Template.FindName("PART_ContentHost", this) is ScrollViewer contentHost && contentHost.Content != null && contentHost.Content is FrameworkElement textBoxView)
{
// 这里解决 TextBoxView 的 Margin 不能设置
textBoxView.Margin = new Thickness(0, 0, 0, 0);
}
}
}

现在修改一下界面,在界面使用创建的 PeedereJiyay 替换原来的控件

        <local:PeedereJiyay Width="100" HorizontalAlignment="Center" VerticalAlignment="Center">

        </local:PeedereJiyay>

只要是单独使用文本,可以尝试继承 TextBox 的类。如果是使用其他控件,建议使用修改 Padding 的方法

c# - How to set the margin on a internal TextBoxView in wpf - Stack Overflow

最新文章

  1. 【BZOJ-2892&amp;1171】强袭作战&amp;大sz的游戏 权值线段树+单调队列+标记永久化+DP
  2. geometric median
  3. 通过j-interop访问WMI实例代码
  4. (旧)子数涵数&#183;Flash——影片剪辑的事件操作
  5. linux设备驱动归纳总结(三):7.异步通知fasync【转】
  6. tilemap坐标转换
  7. SharePoint开发 - 自定义导航菜单(三)附其他代码
  8. [App]Xamarin学习资料收集
  9. 解决ie6显示透明图的问题
  10. [译]Stairway to Integration Services Level 14 - 项目转换(SSIS 2008 ~ SSIS 2012)
  11. Sphnix
  12. Swift 简简单单实现手机九宫格手势密码解锁
  13. poj3237 树链部分 边权模板
  14. 控制结构(3): 状态机(state machine)
  15. dwr去除默认错误弹窗
  16. Spring Boot SOAP Webservice例子
  17. Win7下mysql的安装
  18. 工厂模式 Factory MD
  19. Hive 创建表
  20. 常用类及 LeetCode 每日一题

热门文章

  1. composer本地安装文档 - CSDN博客
  2. 全面解析vue-cli生成的项目中使用其他库(js库、css库)
  3. 将jacoco集成到测试工具平台
  4. CISC和RISC是什么?它们的特点和区别?
  5. Node.js模拟发起http请求从异步转同步的5种方法
  6. Spring_Aop基于配置文件
  7. dialog的进度条
  8. TCP/IP 协议栈学习代码
  9. 【md5加密】不可逆之简单例子原理
  10. Array操作的方法