【问题标题】:Edit Datagrid row background based on object value根据对象值编辑 Datagrid 行背景
【发布时间】:2013-11-28 14:10:03
【问题描述】:

我有以下class

public class Order
{
    public int Id { get; set; }
    public string OrdName { get; set; }
    public int Quant { get; set; }
    public int Supplied { get; set; }
}

还有这个DataGrid:

<DataGrid x:Name="dgOrders" Margin="5" CanUserAddRows="False" CanUserDeleteRows="False"
              SelectionMode="Extended" ItemsSource="{Binding}"
              SelectionUnit="FullRow" VerticalScrollBarVisibility="Auto"
              Height="300" Width="700" HorizontalAlignment="Left" AutoGenerateColumns="False" Grid.Row="2">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Order Name" Binding="{Binding OrdName}" IsReadOnly="True"/>
            <DataGridTextColumn Header="Quantity" Binding="{Binding Quant}" IsReadOnly="True"/>
            <DataGridTextColumn Header="Supplied" Binding="{Binding Supplied}" IsReadOnly="True"/>
        </DataGrid.Columns>
</DataGrid>

我想要的是,当 QuantitySupplied 属性相等时,行背景颜色会改变。
我用Event TriggerConverter 尝试了它,但没有运气(可能我没有在xaml 中正确实现它们)。 也尝试从后面的代码中执行此操作也不起作用(尝试获取像 this suggests 这样的行实例,但我一直为该行获取 null)。

【问题讨论】:

    标签: c# wpf datagrid .net-4.0


    【解决方案1】:

    不能在DataTriggerValue 属性上设置Binding。因此,您需要在数据类型类中添加一个额外的属性:

    public bool AreQuantityAndSuppliedEqual
    {
        return Quantity == Supplied;
    }
    

    那么,有了这个属性,你就可以使用下面的Style

    <Style x:Key="EqualRowStyle" TargetType="{x:Type DataGridRow}">
        <Style.Triggers>
            <DataTrigger Binding="{Binding AreQuantityAndSuppliedEqual}" Value="True">
                <Setter Property="Background" Value="LightGreen" />
            </DataTrigger>
        </Style.Triggers>
    </Style>
    

    它会这样使用:

    <DataGrid ItemsSource="{Binding YourItems}" 
        RowStyle="{StaticResource EqualRowStyle}" ... />
    

    【讨论】:

    • 谢谢谢里登。只是一个小的更正,我认为绑定应该是新的属性名称而不是IsSelected
    • 是的,抱歉,该属性来自我正在使用的测试类。我现在已经更新了...感谢您指出这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-31
    • 2015-04-20
    • 1970-01-01
    • 2011-03-30
    • 1970-01-01
    • 2020-06-02
    相关资源
    最近更新 更多