要实现这一点,您需要定义一个自定义 Behavior,首先确保添加 System.Windows.Interactivity 命名空间(它是 Expression.Blend.Sdk 的一部分 em>,使用 NuGet 安装它:Install-Package Expression.Blend.Sdk),这里是一个基本的实现(感谢@Itzalive):
public class NumLinesBehaviour : Behavior<TextBlock>
{
public static readonly DependencyProperty MaxLinesProperty =
DependencyProperty.RegisterAttached(
"MaxLines",
typeof(int),
typeof(NumLinesBehaviour),
new PropertyMetadata(default(int), OnMaxLinesPropertyChangedCallback));
public static void SetMaxLines(DependencyObject element, int value)
{
element.SetValue(MaxLinesProperty, value);
}
public static int GetMaxLines(DependencyObject element)
{
return (int)element.GetValue(MaxLinesProperty);
}
private static void OnMaxLinesPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is TextBlock element) element.MaxHeight = GetLineHeight(element) * GetMaxLines(element);
}
public static readonly DependencyProperty MinLinesProperty =
DependencyProperty.RegisterAttached(
"MinLines",
typeof(int),
typeof(NumLinesBehaviour),
new PropertyMetadata(default(int), OnMinLinesPropertyChangedCallback));
public static void SetMinLines(DependencyObject element, int value)
{
element.SetValue(MinLinesProperty, value);
}
public static int GetMinLines(DependencyObject element)
{
return (int)element.GetValue(MinLinesProperty);
}
private static void OnMinLinesPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is TextBlock element) element.MinHeight = GetLineHeight(element) * GetMinLines(element);
}
private static double GetLineHeight(TextBlock textBlock)
{
double lineHeight = textBlock.LineHeight;
if (double.IsNaN(lineHeight))
lineHeight = Math.Ceiling(textBlock.FontSize * textBlock.FontFamily.LineSpacing);
return lineHeight;
}
}
现在假设您有一个DataGrid 绑定到具有“Name”属性的TestClass 的ObservableCollection,NumLinesBehaviour Behavior 的基本用法如下:
<Window ...
xmlns:local="clr-namespace:YourNameSpace"
Title="MainWindow" Height="350" Width="525" DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Window.Resources>
<DataTemplate x:Key="CellTemplate">
<StackPanel Orientation="Horizontal">
<TextBlock
Width="200"
TextWrapping="Wrap"
local:NumLinesBehaviour.MaxLines="2"
TextTrimming="WordEllipsis"
LineStackingStrategy="BlockLineHeight"
Text="{Binding Name}"/>
</StackPanel>
</DataTemplate>
</Window.Resources>
<Grid>
<DataGrid ItemsSource="{Binding DgCollection}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTemplateColumn Header="Name" CellTemplate="{StaticResource CellTemplate}" />
</DataGrid.Columns>
</DataGrid>
</Grid>
确保将TextBlock 的TextTrimming 设置为“WordEllipsis”。
更新
输出看起来像这样: