我有一个数据网格:
<DataGrid x:Name="grid1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" ItemsSource="{Binding}" IsReadOnly="True"
Loaded="grid1_Loaded" AutoGeneratingColumn="grid1_AutoGeneratingColumn" SelectionUnit="Cell" MouseMove="Grid1_MouseMove" LoadingRow="grid1_LoadingRow" MouseLeave="grid1_MouseLeave">
<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 trimmedVisibilityConverter}}">
<ToolTip.Content>
<TextBlock Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Content.Text}"/>
</ToolTip.Content>
</ToolTip>
</TextBlock.ToolTip>
</TextBlock>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</DataGrid.Resources>
<DataGrid.RowStyle>
<Style TargetType="{x:Type DataGridRow}">
<Setter Property="Foreground" Value="Red"/>
<Style.Triggers>
<DataTrigger Binding="{Binding Расторжение}" Value="{x:Null}">
<Setter Property="Foreground" Value="Black"></Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
</DataGrid>
和转换器:
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;//Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
工具提示,在修剪单元格内容时打开,位于DataGrid.Resources
部分,我从here中获得。它可以工作,但是现在,当我单击任何单元格时,它看起来像这样:
当我选择一个或多个单元格时,其中的所有值都会消失,并且单元格不会突出显示... DataGrid
的项目来源为DataTable
(如果有关系的话)。如何解决此问题?
很有趣!只需设置DataGrid.CellStyle
即可重现该问题。
我认为问题是Background
中的ControlTemplate
颜色是白色,因此您看不到选择。
将Background="{TemplateBinding Background}"
和Foreground="{TemplateBinding Foreground}"
添加到TextBlock