我正在尝试在选择DataGridRow时更改DataGridHyperlinkColumn的颜色,但随后失去焦点。它似乎不尊重以下内容:
<Style TargetType="Hyperlink">
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGridRow}}, Path=IsSelected}" Value="True">
<Setter Property="Foreground" Value="White"/>
</DataTrigger>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Foreground" Value="Red"/>
</Trigger>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGridRow}}, Path=IsFocused}" Value="False">
<Setter Property="Foreground" Value="Blue"/>
</DataTrigger>
</Style.Triggers>
</Style>
答案 0 :(得分:1)
问题是DataGridRow始终没有聚焦,它是聚焦的单元格:
<DataTrigger Binding="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGridCell}}, Path=IsFocused}" Value="False">
像这样绑定到父DataGridCell只有在你有单列的情况下才有效。如果您有多个列,单元格旁边的单元格包含HyperLink可能会被聚焦,那么您不能简单地使用RelativeSource绑定绑定到父单元格并检查其IsFocused属性。
然后你必须做一些更复杂的事情,例如处理DataGrid的GotFocus / LostFocus路由事件并将其Tag属性设置为true / false:
private void dg_GotFocus(object sender, RoutedEventArgs e)
{
dg.Tag = true;
}
private void dg_LostFocus(object sender, RoutedEventArgs e)
{
dg.Tag = false;
}
然后,您可以将DataTrigger绑定到DataGrid的Tag属性,而不是绑定到父DataGridCell的IsFocused属性:
<DataGrid x:Name="dg" GotFocus="dg_GotFocus" LostFocus="dg_LostFocus">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Text}" />
<DataGridHyperlinkColumn Binding="{Binding Link}">
<DataGridHyperlinkColumn.CellStyle>
<Style TargetType="DataGridCell">
<Style.Resources>
<local:Converter x:Key="converter" />
<Style TargetType="Hyperlink">
<Setter Property="Foreground" Value="Chocolate"></Setter>
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGridRow}}, Path=IsSelected}" Value="True">
<Setter Property="Foreground" Value="White"/>
</DataTrigger>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Foreground" Value="Red"/>
</Trigger>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}, Path=Tag}"
Value="False">
<Setter Property="Foreground" Value="Blue"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Style.Resources>
</Style>
</DataGridHyperlinkColumn.CellStyle>
</DataGridHyperlinkColumn>
</DataGrid.Columns>
</DataGrid>
感谢mm8,按预期工作。这确实产生了一个意想不到的问题。现在没有遵守单元格填充。我会在哪里应用类似&lt; Setter Property =“Padding”Value =“10,5,10,5”/&gt;
在列的ElementStyle中:
<DataGridHyperlinkColumn Binding="{Binding Link}">
<DataGridHyperlinkColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="Padding" Value="10,5,10,5" />
</Style>
</DataGridHyperlinkColumn.ElementStyle>
<DataGridHyperlinkColumn.CellStyle>
...
</DataGridHyperlinkColumn>