[英]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.