这有点长,但我会使用样式选择器来完成这项工作,
作为示例,我在以下窗口中设置了数据网格。
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Title="MainWindow" Height="350" Width="525" DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Window.Resources>
<local:RowStyleSelector x:Key="styleSelector"/>
</Window.Resources>
<Grid>
<DataGrid ItemsSource="{Binding Items}" RowStyleSelector="{StaticResource styleSelector}"/>
</Grid>
</Window>
样式选择器在下面的代码中定义,请注意 TestClass 表示您要放入网格的对象。
RowStyleSelector 类将为添加到网格的每一行运行一次 SelectStyle 方法。
public partial class MainWindow : Window
{
public ObservableCollection<TestClass> Items
{
get { return (ObservableCollection<TestClass>)GetValue(ItemsProperty); }
set { SetValue(ItemsProperty, value); }
}
public static readonly DependencyProperty ItemsProperty = DependencyProperty.Register("Items", typeof(ObservableCollection<TestClass>), typeof(MainWindow), new PropertyMetadata(null));
public MainWindow()
{
InitializeComponent();
Items = new ObservableCollection<TestClass>();
for (int i = 0; i < 100; i++)
Items.Add(new TestClass()
{
ID = i,
Text = "Text for row " + i.ToString()
});
}
}
public class RowStyleSelector : StyleSelector
{
public override Style SelectStyle(object item, DependencyObject container)
{
TestClass targetIem = item as TestClass;
if (targetIem != null)
{
// You can work with your data here.
if (targetIem.ID == 0)
{
// Locate and return the style for when ID = 0.
return (Style)Application.Current.FindResource("ResourceName");
}
else
return base.SelectStyle(item, container);
}
else
return base.SelectStyle(item, container);
}
}
public class TestClass
{
public int ID { get; set; }
public string Text { get; set; }
}
编辑:针对下面的评论,请参阅修改后的 RowStyleConverter,您将不需要 TestClass。
public class RowStyleSelector : StyleSelector
{
public override Style SelectStyle(object item, DependencyObject container)
{
System.Data.DataRow targetItem = item as System.Data.DataRow;
if (targetItem != null)
{
// You can work with your data here.
if ((int)targetItem["IDColumn"] == 0)
{
// Locate and return the style for when ID = 0.
return (Style)Application.Current.FindResource("ResourceName");
}
else
return base.SelectStyle(item, container);
}
else
return base.SelectStyle(item, container);
}
}