从DataGridRow按字段获取行内容

时间:2013-10-31 12:52:06

标签: c# .net wpf datagrid

我的应用程序中有一些DataGrid列有几列。我需要在某些字段内容的情况下使用不同的行前景色。我在LoadingRow事件中使用以下回调:

 void userGrid_LoadingRow(object sender, DataGridRowEventArgs e){

            if (e.Row.Item != null){  
                // check some row's field value               
                ...
                // modify row forecolor
                e.Row.Foreground = new SolidColorBrush(Colors.Red);
                ...
            }
        }

但是如何通过它的名称或索引来获取某个行的字段的值?

1 个答案:

答案 0 :(得分:1)

   void userGrid_LoadingRow(object sender, DataGridRowEventArgs e)
   {
        var dataGrid = (DataGrid)sender;
        IEnumrable<DataGridRow> rows = dataGrid.Items.Where(r =>  (r.DataContext as YourItemsSourceEntity).SomeProperty == yourCondition)
   }

或者我会在ItemsSource中添加一个条件。

        public class YourItemsSourceEntity
        {
             public bool IsSomething { get; }
        } 

xaml:

     <DataGrid ItemsSource="{Binding Items}">
        <DataGrid.ItemContainerStyle>
            <Style TargetType="DataGridRow">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding IsSomething}" Value="True">
                        <Setter Property="Background" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </DataGrid.ItemContainerStyle>                
    </DataGrid>          

以下评论:这是你的意思吗?

    void userGrid_LoadingRow(object sender, DataGridRowEventArgs e)
   {
        var item = e.Row.DataContext as (YourItemsSourceEntity);
        var id = item.ID ;   
   }