c# – WPF工具包DataGridCell样式DataTrigger
发布时间:2020-12-16 01:35:57 所属栏目:百科 来源:网络整理
导读:如果在DataGrid中更新了值,我试图将单元格的颜色更改为黄色. 我的XAML: toolkit:DataGrid x:Name="TheGrid" ItemsSource="{Binding}" IsReadOnly="False" CanUserAddRows="False" CanUserResizeRows="False" AutoGenerateColumns="False" CanUserSortColumn
|
如果在DataGrid中更新了值,我试图将单元格的颜色更改为黄色.
我的XAML: <toolkit:DataGrid x:Name="TheGrid"
ItemsSource="{Binding}"
IsReadOnly="False"
CanUserAddRows="False"
CanUserResizeRows="False"
AutoGenerateColumns="False"
CanUserSortColumns="False"
SelectionUnit="CellOrRowHeader"
EnableColumnVirtualization="True"
VerticalScrollBarVisibility="Auto"
HorizontalScrollBarVisibility="Auto">
<toolkit:DataGrid.CellStyle>
<Style TargetType="{x:Type toolkit:DataGridCell}">
<Style.Triggers>
<DataTrigger Binding="{Binding IsDirty}" Value="True">
<Setter Property="Background" Value="Yellow"/>
</DataTrigger>
</Style.Triggers>
</Style>
</toolkit:DataGrid.CellStyle>
</toolkit:DataGrid>
网格绑定到数组列表(显示类似于excel的值表).数组中的每个值都是一个包含IsDirty依赖项属性的自定义对象.更改值时,将设置IsDirty属性. 当我运行这个: >更改第1列中的值=整行变为黄色 我希望只有更改的单元格变成黄色,无论它在哪一列.你看到我的XAML有什么问题吗? 解决方法
发生这种情况的原因是因为DataContext设置在行级别,并且不会为每个DataGridCell更改.因此,当您绑定到IsDirty时,它会绑定到行级数据对象的属性,而不是单元级别的属性.
由于您的示例显示您将AutoGenerateColumns设置为false,因此我假设您自己生成的列具有类似DataGridTextColumn的类,其中Binding属性设置为绑定到实际值字段.要将单元格样式更改为黄色,您必须在每个DataGridColumn上更改CellStyle,如下所示: foreach (var column in columns)
{
var dataColumn =
new DataGridTextColumn
{
Header = column.Caption,Binding = new Binding(column.FieldName),CellStyle =
new Style
{
TargetType = typeof (DataGridCell),Triggers =
{
new DataTrigger
{
Binding = new Binding(column.FieldName + ".IsDirty"),Setters =
{
new Setter
{
Property = Control.BackgroundProperty,Value = Brushes.Yellow,}
}
}
}
}
};
_dataGrid.Columns.Add(dataColumn);
}
您可以尝试使用DataGridColumn.CellStyle更改每个单元格的DataContext.也许只有这样你才能直接从网格级样式将单元格绑定到’IsDirty’,而不是单独为每个列执行.但我没有实际数据模型,你必须测试这个. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
