C# WPF DataGrid Change cells color by value

末鹿安然 提交于 2019-12-24 11:28:00

问题


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"):


回答1:


I have made a simple sample to just guide you how it can be done

Xaml code

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

The code behind

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

EDIT Just add the UpdateSourceTrigger in the TextBox within the DataTemplate



来源:https://stackoverflow.com/questions/32665722/c-sharp-wpf-datagrid-change-cells-color-by-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!