如何根据数据值修改DataGrid中Border的BorderBrush属性
解决DataGrid行BorderBrush根据数据值动态变化的问题
实现步骤
- 声明转换器资源
在你的XAML根节点(如Window或UserControl)的资源字典中添加转换器实例,注意替换local为CellConverter所在的实际命名空间:
<Window.Resources> <!-- 替换clr-namespace为你的转换器所在命名空间 --> <local:CellConverter x:Key="CellConverter"/> </Window.Resources>
- 修改Border的BorderBrush绑定
在DataGridRowStyle2的模板中,将DGR_Border的固定BorderBrush值替换为绑定到数据模型的目标属性,并应用转换器。假设数据模型中存储优先级的属性名为Priority,请替换为你实际的属性名:
修改后的完整Style代码:
<Style x:Key="DataGridRowStyle2" TargetType="{x:Type DataGridRow}"> <Setter Property="Background" Value="Transparent"/> <Setter Property="SnapsToDevicePixels" Value="true"/> <Setter Property="BorderBrush" Value="Transparent"/> <Setter Property="ValidationErrorTemplate"> <Setter.Value> <ControlTemplate> <TextBlock Foreground="Transparent" Margin="2,0,0,0" Text="!" VerticalAlignment="Center"/> </ControlTemplate> </Setter.Value> </Setter> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type DataGridRow}"> <!-- 修改此处的BorderBrush绑定 --> <Border x:Name="DGR_Border" CornerRadius="5" Background="{TemplateBinding Background}" BorderThickness="2" BorderBrush="{Binding Priority, Converter={StaticResource CellConverter}}" SnapsToDevicePixels="True"> <SelectiveScrollingGrid> <SelectiveScrollingGrid.ColumnDefinitions> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="*"/> </SelectiveScrollingGrid.ColumnDefinitions> <SelectiveScrollingGrid.RowDefinitions> <RowDefinition Height="*"/> <RowDefinition Height="Auto"/> </SelectiveScrollingGrid.RowDefinitions> <DataGridCellsPresenter ItemsPanel="{TemplateBinding ItemsPanel}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/> <DataGridDetailsPresenter Visibility="{TemplateBinding DetailsVisibility}"/> <DataGridRowHeader Visibility="{Binding HeadersVisibility, Converter={x:Static DataGrid.HeadersVisibilityConverter}, ConverterParameter={x:Static DataGridHeadersVisibility.Row}, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"/> </SelectiveScrollingGrid> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style>
若需要明确指定绑定源为当前DataGridRow的DataContext,可使用RelativeSource:
BorderBrush="{Binding Path=Priority, RelativeSource={RelativeSource AncestorType={x:Type DataGridRow}}, Converter={StaticResource CellConverter}}"
- 确认转换器代码
你编写的CellConverter逻辑正确,无需修改,它会根据输入的字符串值返回对应的Brush:
public class CellConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { string input = value as string; switch (input) { case "High": return Brushes.Red; case "Medium": return Brushes.Yellow; case "Low": return Brushes.Green; default: return DependencyProperty.UnsetValue; } } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } }
内容的提问来源于stack exchange,提问作者jirina
相关产品推荐
相关产品推荐

