你可能會尋找像這樣的begavior:
public class TextBlockBehavior : Behavior<TextBlock>
{
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.SizeChanged += AssociatedObject_SizeChanged;
}
protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.SizeChanged -= AssociatedObject_SizeChanged;
}
private void AssociatedObject_SizeChanged(object sender, SizeChangedEventArgs e)
{
TextBlock temp = new TextBlock()
{
Text = AssociatedObject.Text,
LineStackingStrategy = AssociatedObject.LineStackingStrategy,
LineHeight = AssociatedObject.LineHeight,
TextTrimming = TextTrimming.None,
TextWrapping = AssociatedObject.TextWrapping,
Height = AssociatedObject.Height
};
double maxwidth = AssociatedObject.MaxWidth - 10;
double desiredHeight = double.PositiveInfinity;
while (desiredHeight > AssociatedObject.MaxHeight)
{
temp.Measure(new Size(maxwidth, double.PositiveInfinity));
maxwidth += 10;
desiredHeight = temp.DesiredSize.Height;
}
AssociatedObject.MaxWidth = maxwidth;
}
}
請注意,根據當前最大寬度測量臨時TextBlock。使用其所需的尺寸,我們可以決定是增加最大寬度還是無所事事。
您應該設置MaxHeight
和MaxWidth
屬性。測試:
<TextBlock MaxHeight="50" MaxWidth="100" Background="Red" TextTrimming="None" TextWrapping="Wrap" MouseDown="TextBlock_MouseDown">
<i:Interaction.Behaviors>
<local:TextBlockBehavior />
</i:Interaction.Behaviors>
</TextBlock>
和代碼:
private void TextBlock_MouseDown(object sender, MouseButtonEventArgs e)
{
((TextBlock)sender).Text += "AAAA ";
}
您可能需要更改出頭的克隆文本塊或更改邏輯或改變步長(我在這裏選擇10分)。
來源
2017-03-02 09:00:08
Ron