C#WPF DataGrid按值更改单元格颜色 [英] C# WPF DataGrid Change cells color by value
本文介绍了C#WPF DataGrid按值更改单元格颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是WPF的新手,并试图通过其值突出显示Datagrid单元.我已将项目列表加载到DataGrid,并且我想标记所有错误的输入值(表示为值"0"):
I am new to WPF and trying to highlight Datagrid cells by their value. I have loaded a list of items to the DataGrid, and I want to mark all the wrong input values (represented as value "0"):
推荐答案
我制作了一个简单的示例来指导您如何完成
I have made a simple sample to just guide you how it can be done
Xaml代码
<DataGrid x:Name="dataGrid" IsEnabled="True" CanUserAddRows="False" AutoGenerateColumns="False" Width="275" HorizontalAlignment="Left">
<DataGrid.Columns>
<DataGridTextColumn Header="ID" Binding="{Binding ID}" Width="25"/>
<DataGridTextColumn Header="Weight" Binding="{Binding Weight}" Width="25"/>
<DataGridTextColumn Header="Quantity" Binding="{Binding Quantity}" Width="25"/>
<DataGridTemplateColumn Header="Length" Width="25">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox Text="{Binding Length, UpdateSourceTrigger=LostFocus}">
<TextBox.Style>
<Style TargetType="{x:Type TextBox}">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=Length}" Value="0">
<Setter Property="BorderBrush" Value="Red"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Header="Height" Binding="{Binding Height}" Width="25"/>
<DataGridTextColumn Header="Width" Binding="{Binding Width}" Width="25"/>
<DataGridTextColumn Header="X" Binding="{Binding X}" Width="25"/>
<DataGridTextColumn Header="Y" Binding="{Binding Y}" Width="25"/>
<DataGridTextColumn Header="Z" Binding="{Binding Z}" Width="25"/>
</DataGrid.Columns>
</DataGrid>
背后的代码
public partial class MainWindow : Window
{
public ObservableCollection<Model> Source { get; set; }
public MainWindow()
{
InitializeComponent();
Source = new ObservableCollection<Model>
{
new Model {ID=1,Weight=3,Quantity=5,Length=11,Height=12,Width=0,X=1,Y=-1,Z=-1 },
new Model {ID=2,Weight=21,Quantity=23,Length=0,Height=23,Width=11,X=-1,Y=-1,Z=-1 }
};
dataGrid.ItemsSource = Source;
}
}
编辑只需在 DataTemplate
这篇关于C#WPF DataGrid按值更改单元格颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文