想让TextBox的高度自动适应内容
通过设置附加属性attach:TextBoxAttach.AutoHeight
和TextBlock.LineHeight
<TextBox VerticalContentAlignment="Top"
attach:TextBoxAttach.AutoHeight="True"
AcceptsReturn="True"
Text="{Binding Model.Content}"
TextBlock.LineHeight="20"
TextWrapping="Wrap"
VerticalScrollBarVisibility="Visible" />
- 监听AutoHeight属性的变化,当设置为True时,如果对象是textBox,就监听TextBox的
Loaded
,Unloaded
,TextChanged
- 当控件还没Loaded的时候,是无法获取实际行数的
- 在Unloaded事件中取消所有事件的注册
- 控件高度的改变就是很简单的事情了,获取实际的行数和配置的行高,直接设置控件高度即可
有一个问题:当前是在TextChanged中,每次变更都是计算设置控件高度,如果可以监控到行高的变化的话,应该合理一点。或许可以用Tag之类的记录一下旧的行数?
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;
}
}