[英]WPF DataGrid DataTrigger Binding on DataContext property
什么是DataContext属性的正确DataTrigger绑定? 我有一个绑定的数据网格是这样的:
XAML:
<DataGrid x:Name="dataGrid" Grid.Row="4" Grid.ColumnSpan="2"
ItemsSource="{Binding}"
CellStyle="{StaticResource RowStateStyle}"
>
</DataGrid>
在.cs中,网格绑定到DataTable,因此单元格的DataContext是DataRowView,其中包含Row作为属性:
// DataTable containing lots of rows/columns
dataGrid.DataContext = dataTable;
编辑:
参照ASh的解决方案,我编辑了样式并将其放入“未更改和修改的触发器”中:
<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对我有用,如果我
使用DataContext.Row.RowState
路径
不要使用Mode=TwoWay
并设置值时删除枚举名称DataRowState
<DataTrigger Binding="{Binding Path=DataContext.Row.RowState,
RelativeSource={RelativeSource Self}}"
Value="Unchanged">
<Setter Property="Foreground" Value="Red" />
</DataTrigger>
我发现了与此问题相关的另一篇文章
没有默认机制可通知RowState
更改。 但是可以在派生的dataTable类中创建一个:
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类:
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));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.