其他分享
首页 > 其他分享> > WPF的TextBox控件的自动行高

WPF的TextBox控件的自动行高

作者:互联网

想让TextBox的高度自动适应内容

通过设置附加属性attach:TextBoxAttach.AutoHeightTextBlock.LineHeight

<TextBox VerticalContentAlignment="Top" 
    attach:TextBoxAttach.AutoHeight="True"
    AcceptsReturn="True"
    Text="{Binding Model.Content}"
    TextBlock.LineHeight="20" 
    TextWrapping="Wrap"
    VerticalScrollBarVisibility="Visible" />
  1. 监听AutoHeight属性的变化,当设置为True时,如果对象是textBox,就监听TextBox的Loaded,Unloaded,TextChanged
  2. 当控件还没Loaded的时候,是无法获取实际行数的
  3. 在Unloaded事件中取消所有事件的注册
  4. 控件高度的改变就是很简单的事情了,获取实际的行数和配置的行高,直接设置控件高度即可
  5. 有一个问题:当前是在TextChanged中,每次变更都是计算设置控件高度,如果可以监控到行高的变化的话,应该合理一点
public class TextBoxAttach
    {
        public static bool GetAutoHeight(DependencyObject obj)
        {
            return (bool)obj.GetValue(AutoHeightProperty);
        }
        public static void SetAutoHeight(DependencyObject obj, bool value)
        {
            obj.SetValue(AutoHeightProperty, value);
        }
        public static readonly DependencyProperty AutoHeightProperty =
            DependencyProperty.RegisterAttached("AutoHeight", typeof(bool), typeof(TextBoxAttach), new PropertyMetadata(false, OnChanged));

        private static void OnChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (!(d is TextBox textBox))
            {
                return;
            }
            if (textBox != null)
            {
                textBox.Loaded += TextBox_Loaded;
                textBox.Unloaded += TextBox_Unloaded;
                textBox.TextChanged += TextBox_TextChanged;
            }
        }
        private static void TextBox_Unloaded(object sender, RoutedEventArgs e)
        {
            var c = sender as TextBox;
            c.Unloaded -= TextBox_Unloaded;
            c.Loaded -= TextBox_Loaded;
            c.TextChanged -= TextBox_TextChanged;
        }
        private static void TextBox_Loaded(object sender, RoutedEventArgs e)
        {
            var c = sender as TextBox;
            ReSize(c);
        }
        private static void TextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            var c = sender as TextBox;
            if (c.IsLoaded)
                ReSize(c);
        }
        private static void ReSize(TextBox textBox)
        {
            var lines = textBox.LineCount;
            var lineHeight = (double)textBox.GetValue(TextBlock.LineHeightProperty);
            double height = lineHeight * lines;
            textBox.Height = height;
        }
    }

标签:控件,static,Unloaded,Loaded,WPF,TextBox,TextChanged,行高,textBox
来源: https://www.cnblogs.com/marvelTitile/p/15206546.html