解决办法一:这个方法简单一点用后台代码实现
public
static
DataGridRow GetDataGridRow(DataGrid dataGrid,
int
rowIndex)
{
DataGridRow row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(rowIndex);
if
(row ==
null
)
{
dataGrid.UpdateLayout();
row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(rowIndex);
}
return
row;
}
取行Index ,取值再判断一下你的条件,符合就改
调用
DataGridRow drow=GetDataGridRow(dataGrid1, rowIndex)
drow.Foreground = Brushes.Blue;
调用
DataGridRow drow=GetDataGridRow(dataGrid1, rowIndex)
drow.Foreground = Brushes.Blue;
方法二:代码看起来多点。用数据触发器实现
下面的代码的作用是,当值等于23的时候DataGridRow行的字体颜色为红色。
<Style TargetType="{x:Type DataGridRow}"> <Style.Triggers> <DataTrigger Binding="{Binding Age}" Value="23"> <Setter Property="ToolTip"> <Setter.Value> <ToolTip> <TextBlock Text="{Binding Age,StringFormat='年龄:{0}超出'}"/> </ToolTip> </Setter.Value> </Setter> <Setter Property="Foreground" Value="Red" /> </DataTrigger> </Style.Triggers> </Style>
想要操作等于以外的情况时,只能自己写一个值转换类,继承IValueConverter 。
namespace dataGrid_binding.ViewModel { public class AgeConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { int v = 0, p = 0; int.TryParse(value.ToString(), out v); int.TryParse(parameter.ToString(), out p); return v > p; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } }
以下的内容写在Xaml页面上。
<Window x:Class="dataGrid_binding.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:VM="clr-namespace:dataGrid_binding.ViewModel" Title="MainWindow" Height="395" Width="713"> <Window.Resources> <VM:StudentViewModel x:Key="ViewModel" /> <VM:AgeConverter x:Key="AgeConvert" /> <Style TargetType="{x:Type DataGridRow}"> <Style.Triggers> <DataTrigger Binding="{Binding Age,Converter={StaticResource AgeConvert}, ConverterParameter=22}" Value="True"> <Setter Property="ToolTip"> <Setter.Value> <ToolTip> <TextBlock Text="{Binding Age,StringFormat='年龄:{0}超出'}"/> </ToolTip> </Setter.Value> </Setter> <Setter Property="Foreground" Value="Red" /> </DataTrigger> </Style.Triggers> </Style> </Window.Resources>
<DataTrigger Binding="{Binding Age,Converter={StaticResource AgeConvert},ConverterParameter=22}" Value="True">
上面这句的意思就是Binding了数据Age,转换这个值,对应上面的值转换类,当值大于ConverterParameter传过去的值的时候,做操作。
这个样式就对应了DataGrid中绑定了Age字段的列。