繁体   English   中英

WPF 动态更改 DataGrid 单元格样式

[英]WPF Change DataGrid Cell Style dynamically

我有两个单元格模板,一个用于“只读”,另一个用于“CellEditing”。 一个按钮正在绑定一个命令来将一个变量(IsEditable)切换为真/假。 当我单击按钮时,直到双击单元格,样式才会改变。

我的问题是,如何在不双击单元格的情况下动态更改 DataGrid 单元格样式。

我的 XAML:

<DataTemplate x:Key="ReadOnlyTemplate">
  <TextBox Text="{Binding ProductionName}">
    <TextBox.Style>
      <Style TargetType="{x:Type TextBox}">
        <Setter Property="IsEnabled" Value="False"/>
        <Setter Property="Background" Value="Black"/>
        <Setter Property="Foreground" Value="White"/>
      </Style>
    </TextBox.Style>
  </TextBox>
</DataTemplate>

<DataTemplate x:Key="CellEditingTemplate">
  <TextBox Text="{Binding ProductionName}">
    <TextBox.Style>
      <Style TargetType="{x:Type TextBox}">
        <Setter Property="IsEnabled" Value="False"/>
        <Setter Property="Background" Value="Black"/>
        <Setter Property="Foreground" Value="White"/>
        <Style.Triggers>
          <DataTrigger Binding="{Binding IsEditable}" Value="True">
            <Setter Property="IsEnabled" Value="True"/>
            <Setter Property="Background" Value="White"/>
            <Setter Property="Foreground" Value="Black"/>
          </DataTrigger>
        </Style.Triggers>
      </Style>
    </TextBox.Style>
  </TextBox>
</DataTemplate>

...

<DataGridTemplateColumn Header="Name" CellTemplate="{StaticResource ReadOnlyTemplate}" CellEditingTemplate="{StaticResource CellEditingTemplate}"/>

CellEditingTemplate 仅在您已经编辑单元格时应用。 您想要的是在不编辑时修改样式。 尝试这个:

<DataTemplate x:Key="ProductionNameTemplate" >
    <TextBox Text="{Binding ProductionName}">
        <TextBox.Style>
            <Style TargetType="{x:Type TextBox}">
                <Setter Property="IsEnabled" Value="False"/>
                <Setter Property="Background" Value="Black"/>
                <Setter Property="Foreground" Value="White"/>
                <Style.Triggers>
                    <DataTrigger Binding="{Binding IsEditable}" Value="True">
                        <Setter Property="IsEnabled" Value="True"/>
                        <Setter Property="Background" Value="White"/>
                        <Setter Property="Foreground" Value="Black"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </TextBox.Style>
    </TextBox>
</DataTemplate>

并将其应用为 CellTemplate。

<DataGridTemplateColumn Header="Name" CellTemplate="{StaticResource ProductionNameTemplate}"/>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM