我在DataGrid
中有一列显示短信。不幸的是它太长了。因此,我在textblock
使用TextWrapping = "Wrap"
显示多行。我不想要它。我只想显示前两行,最后添加省略号(...)
有办法吗?
答案 0 :(得分:1)
要实现这一点,您需要定义自定义Behavior
,首先确保添加 System.Windows.Interactivity 命名空间(它是 Expression.Blend.Sdk的一部分) ,使用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
ObservableCollection
TestClass
Name
NumLinesBehaviour
与&#34; Behavior
&#34;属性,<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>
TextTrimming
的基本用法如下:
TextBlock
务必将WordEllipsis
的{{1}}设置为&#34; i
&#34;。
<强>更新强>
输出看起来像这样: