简体   繁体   中英

WPF Change DataGrid Cell Style dynamically

I have two cell template, one is for "ReadOnly" the other is for "CellEditing". And a button is binding a command to switch a variable (IsEditable) to be true/false. When I click the button, the style does not change until double click the cell.

My question is, how to change DataGrid Cell Style dynamically without double click the cell.

My 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 is only applied when you already edit the cell. What you want is to modify the style while you are not editing. Try this:

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

And apply this as CellTemplate.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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