【问题标题】:WPF Datagrid-Change background color of the row for which the button is clickedWPF Datagrid - 更改单击按钮所在行的背景颜色
【发布时间】:2012-12-08 15:35:09
【问题描述】:

我的 wpf 应用程序中有一个数据网格。我希望当用户单击数据网格中的任何按钮时,相应的行应该是红色的。我认为我们可以通过使用事件触发器来做到这一点,但我真的不知道如何使用它。

    <DataGrid x:Name="dgEmp" Grid.Row="1" AutoGenerateColumns="False" CanUserAddRows="False" >          
        <DataGrid.Columns>
        <DataGridTextColumn Header="Name" Width="*" Binding="{Binding Path=Name}"></DataGridTextColumn>
        <DataGridTextColumn Header="Age" Width="*" Binding="{Binding Path=Age}"></DataGridTextColumn>
            <DataGridTemplateColumn Header="Delete" Width="*">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <Button Content="Delete selected row"></Button>                              
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
    </DataGrid>

【问题讨论】:

    标签: c# wpf datagrid background


    【解决方案1】:

    您可以在每一行中设置一个颜色属性,将其绑定到行背景颜色并随着 SelectedItem 的变化而更改它。

    <DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
           <Setter Property="Background" Value="{Binding RowColour}" />
        </Style>
    </DataGrid.RowStyle>
    

    【讨论】:

    • 对我不起作用。 &lt;DataGrid.RowBackground&gt; &lt;SolidColorBrush Color="{Binding RowColor}" /&gt; &lt;/DataGrid.RowBackground&gt;&lt;DataGrid.Resources&gt; &lt;Style TargetType="DataGridRow"&gt; &lt;Setter Property="Background" Value="{Binding RowColor}" /&gt; &lt;/Style&gt; &lt;/DataGrid.Resources&gt; 也没有在这些情况下,我将行的背景设置为表单的颜色。
    • @Astrogator 您是否遇到任何绑定错误?您是绑定到集合或祖先或集合中的颜色吗?这确实有效。
    • 诀窍是:如果RowColor 的类型为Color,则必须将其包装在&lt;SolidColorBrush&gt; 元素中,如stackoverflow.com/questions/7339509 的回答所示。否则RowColor 必须是Brush
    猜你喜欢
    • 1970-01-01
    • 2014-10-09
    • 2017-08-02
    • 1970-01-01
    • 2014-10-10
    • 2019-04-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多