【问题标题】:How to change background of the template item, on selecting DataGridCell如何在选择 DataGridCell 时更改模板项的背景
【发布时间】:2021-11-08 16:46:12
【问题描述】:

我需要根据是否选择数据单元格来更改 DataGridTemplateColumn 单元格内的文本框的背景颜色。

目前我设法做的是,更改模板单元格的背景颜色,由于错误管理而变得无用。

因此,我想更改文本框的背景,并在选择更改时将其恢复。

  <DataGrid.Resources>
                <Style TargetType="{x:Type DataGridRow}">
                    <Style.Triggers>
                        <Trigger Property="IsSelected" Value="True">
                            <Setter Property="Background" Value="DarkBlue"/>
                            <Setter Property="Foreground" Value="Black"/>
                        </Trigger>
                    </Style.Triggers>
                </Style>
            </DataGrid.Resources>

            <DataGrid.Columns>

                <DataGridTemplateColumn IsReadOnly="True" MinWidth="150" Width="*">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <TextBox  Text="{Binding Path=TwoDLineName, Mode=TwoWay,UpdateSourceTrigger=LostFocus, ValidatesOnDataErrors=True, NotifyOnValidationError=True}"
                                 HorizontalAlignment="Stretch"  Style="{StaticResource TextBoxValidated}"/>
                              
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>

【问题讨论】:

    标签: c# wpf datagrid


    【解决方案1】:

    您可以将Style 与绑定到父行的IsSelected 属性的DataTrigger 一起使用:

    <DataGridTemplateColumn IsReadOnly="True" MinWidth="150" Width="*">
        <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
                <TextBox Text="{Binding Path=TwoDLineName, Mode=TwoWay,UpdateSourceTrigger=LostFocus, ValidatesOnDataErrors=True, NotifyOnValidationError=True}">
                    <TextBox.Style>
                        <Style TargetType="TextBox" BasedOn="{StaticResource TextBoxValidated}">
                            <Style.Triggers>
                                <DataTrigger Binding="{Binding IsSelected,
                                    RelativeSource={RelativeSource AncestorType=DataGridRow}}"
                                             Value="True">
                                    <Setter Property="Background" Value="Red" />
                                </DataTrigger>
                            </Style.Triggers>
                        </Style>
                    </TextBox.Style>
                </TextBox>
            </DataTemplate>
        </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>
    

    【讨论】:

      猜你喜欢
      • 2015-04-05
      • 1970-01-01
      • 1970-01-01
      • 2011-11-18
      • 1970-01-01
      • 1970-01-01
      • 2021-02-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多