C#WPF DataGrid按值更改单元格颜色

时间:2015-09-19 07:48:48

标签: c# wpf datagrid highlight

我是WPF的新手,并尝试按其值突出显示Datagrid单元格。 我已经将一个项目列表加载到DataGrid,我想标记所有错误的输入值(表示为值“0”):

enter image description here

1 个答案:

答案 0 :(得分:2)

我制作了一个简单的示例来指导您如何完成

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;
    }
}

修改 只需在UpdateSourceTrigger

中的TextBox中添加DataTemplate即可