我的应用程序使用C#和WPF(.net framework 4.0)运行。我的目标是要有一个DataGrid,其中的单元格中的文本用省略号修饰,并且仅当单元格中的文本实际被修剪时,才自动显示工具提示,并显示全文。
解决方案1:我目前正在使用此方法来了解文本是否被修剪:http://tranxcoder.wordpress.com/2008/10/12/customizing-lookful-wpf-controls-take-2/问题在于它仅在我调整列大小时才有效。首次加载DataGrid,对列进行排序或更新DataGrid的ItemSource时,不会显示工具提示。
解决方案2:我也尝试过此操作:http://www.scottlogic.com/blog/2011/01/31/automatically-showing-tooltips-on-a-trimmed-textblock-silverlight-wpf.html但是工具提示永远不会出现在我的DataGrid单元上,尽管它可以与孤立的文本块一起正常工作。
我正在寻找简单的方法来改进解决方案1,并使其在所有情况下都可以在我的DataGrid中使用,或者可能使用其他方法。
解决方案1的样式:
<UserControl.Resources>
<Style x:Key="TextColumnElementStyle" TargetType="TextBlock" BasedOn="{StaticResource TextBlockService}">
<Style.Setters>
<Setter Property="TextWrapping" Value="NoWrap" />
<Setter Property="TextTrimming" Value="WordEllipsis" />
</Style.Setters>
</Style>
</UserControl.Resources>
The source code of the TextBlockService
解决方案1的DataGrid:
<DataGrid ItemsSource="{Binding IssueList}" tbs:TextBlockService.AutomaticToolTipEnabled="True">
<DataGrid.Columns>
<DataGridTextColumn Header="Description" Binding="{Binding Description}"
ElementStyle="{StaticResource TextColumnElementStyle}">
</DataGrid.Columns>
</DataGrid>
谢谢
基于an answer by xr280xr,我已经找到了完美的解决方案。它在任何情况下都可以直接使用,无需使用其他代码。
我输入<DataGrid.Resources>
的样式:
<Style TargetType="{x:Type DataGridCell}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type DataGridCell}">
<TextBlock Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Content.Text}" TextTrimming="CharacterEllipsis">
<TextBlock.ToolTip>
<ToolTip Visibility="{Binding RelativeSource={RelativeSource Self}, Path=PlacementTarget, Converter={StaticResource TrimToVisConverter}}">
<ToolTip.Content>
<TextBlock Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Content.Text}"/>
</ToolTip.Content>
</ToolTip>
</TextBlock.ToolTip>
</TextBlock>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Converter={StaticResource TrimToVisConverter}
的来源:
public class TrimmedTextBlockVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null) return Visibility.Collapsed;
FrameworkElement textBlock = (FrameworkElement)value;
textBlock.Measure(new System.Windows.Size(Double.PositiveInfinity, Double.PositiveInfinity));
if (((FrameworkElement)value).ActualWidth < ((FrameworkElement)value).DesiredSize.Width)
return Visibility.Visible;
else
return Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
我还不能发表评论,我缺少要点。
但是我只是想向已接受的答案代码添加一个额外的提示,以供像我这样想要使用它的菜鸟使用。
如果要将Converter链接到其代码,请确保将其添加到Window / UserControl资源中:
<Window.Resources>
<local:TrimmedTextBlockVisibilityConverter x:Key="TrimToVisConverter" />
</Window.Resources>
再次抱歉...! :)