WPF DataGrid DataTrigger Binding on DataContext property
什么是DataContext属性的正确DataTrigger绑定?
我有一个绑定的数据网格是这样的:
XAML:
1 2 3 4 5 | <DataGrid x:Name="dataGrid" Grid.Row="4" Grid.ColumnSpan="2" ItemsSource="{Binding}" CellStyle="{StaticResource RowStateStyle}" > </DataGrid> |
在.cs中,网格绑定到DataTable,因此单元格的DataContext是DataRowView,其中包含Row作为属性:
1 2 | // DataTable containing lots of rows/columns dataGrid.DataContext = dataTable; |
编辑:
参照ASh的解决方案,我编辑了样式并将其放入"未更改和修改的触发器"中:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <Style x:Key="RowStateStyle" TargetType="{x:Type DataGridCell}"> <Style.Triggers> <DataTrigger Binding="{Binding Path=DataContext.Row.RowState, RelativeSource={RelativeSource Self}}" Value="Unchanged"> <Setter Property="Foreground" Value="Green" /> </DataTrigger> <DataTrigger Binding="{Binding Path=DataContext.Row.RowState, RelativeSource={RelativeSource Self}}" Value="Modified"> <Setter Property="Foreground" Value="Yellow" /> </DataTrigger> <DataTrigger Binding="{Binding Path=Content.Text, RelativeSource={RelativeSource Self}}" Value="test"> <Setter Property="Foreground" Value="Red" /> </DataTrigger> </Style.Triggers> </Style> |
在Content.Text上触发完全正常,未更改也是如此。 但是,当我修改单元格(因此DataRowState = Modified)时,什么也没有发生,并且颜色保持绿色。 有什么办法吗?
DataTrigger对我有用,如果我
使用
不要使用
并在设置Value时删除枚举名称
1 2 3 4 5 | <DataTrigger Binding="{Binding Path=DataContext.Row.RowState, RelativeSource={RelativeSource Self}}" Value="Unchanged"> <Setter Property="Foreground" Value="Red" /> </DataTrigger> |
我发现了与此问题相关的另一篇文章
WpfToolkit DataGrid:高亮显示已修改的行
没有默认机制通知
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | public class DataTableExt: DataTable { protected override DataRow NewRowFromBuilder(DataRowBuilder builder) { return new DataRowExt(builder); } protected override void OnRowChanged(DataRowChangeEventArgs e) { base.OnRowChanged(e); // row has changed, notifying about changes var r = e.Row as DataRowExt; if (r!= null) r.OnRowStateChanged(); } } |
带有派生的dataRow类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | public class DataRowExt: DataRow, INotifyPropertyChanged { protected internal DataRowExt(DataRowBuilder builder) : base(builder) { } internal void OnRowStateChanged() { OnPropertyChanged("RowState"); } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(string propertyName) { var handler = PropertyChanged; if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); } } |