我试图循环数据网格中的每一行,拉出一个列值,将此值传递给一个方法,并根据方法的结果设置该行的样式.
在发现我无法循环遍历数据网格的行之后,我发现这篇文章详细说明了它的可行性.
我稍微修改了一下,以便我使用datarowview对象.
我现在面临的问题是
var dgRow = grid.ItemContainerGenerator.ContainerFromItem(r) as DataGridRow;
Run Code Online (Sandbox Code Playgroud)
总是返回null.
请有人可以告诉我为什么会发生这种情况,如果他们能看到更容易的方法.
如果您需要更多信息,请告诉我.
继承我的代码:
private void colorArchived( DataGrid grid , GX3MaterialSelectionData data)
{
var row = GetDataGridRows(grid);
foreach (DataRowView r in row)
{
var dgRow = grid.ItemContainerGenerator.ContainerFromItem(r) as DataGridRow;
int val = int.Parse(r.Row[0].ToString());
if ( data.IsArchived(val) )
{
// style will be defined in xaml
dgRow.Style = mystyle;
}
}
}
public IEnumerable<DataRowView> GetDataGridRows(DataGrid grid)
{
var itemsSource = grid.ItemsSource as IEnumerable;
if (null == itemsSource) yield return null;
foreach (var item in itemsSource)
{
var row = item;
if (null != row) yield return (DataRowView)row;
}
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,您可以使用 StyleSelector。
public class RowStyle : StyleSelector
{
public override Style SelectStyle(object item, DependencyObject container)
{
// here the item property is the entity that the grid row is bound to.
// check whatever values you want on it and locate a matching style with
// find resource.
// return a reference to the correct style here
// or allow this to run if you want the default style.
return base.SelectStyle(item, container);
}
}
Run Code Online (Sandbox Code Playgroud)
要在数据网格上使用它,您需要设置 RowStyleSelector 属性。
<Window x:Class="Rich.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Rich"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<local:RowStyle x:Key="styleSelector"/>
</Window.Resources>
<Grid>
<DataGrid ItemsSource="{Binding Items}" RowStyleSelector="{StaticResource styleSelector}">
<DataGrid.Columns>
<DataGridTextColumn Header="test" Binding="{Binding Test1}"/>
<DataGridTextColumn Header="test2" Binding="{Binding Test2}"/>
<DataGridTextColumn Header="test3" Binding="{Binding Test3}"/>
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
Run Code Online (Sandbox Code Playgroud)