根據數值變更 WPF DataGrid 儲存格顏色
在 WPF DataGrid 中,根據特定值自訂單一儲存格的外觀可以增強資料視覺化效果。但是,如果在只想為特定單元格著色時,出現整行高亮顯示的問題,則可能需要檢查程式碼以識別根本原因。
初始程式碼設定了 DataGrid.CellStyle,但此方法會影響整行,因為 DataContext 設定為行而不是單一儲存格。為了解決這個問題,建議定位特定列並根據不同的內容(例如文字、組合方塊和複選框)自訂其外觀。以下是如何更改名稱為“John”的單元格背景的範例。
<code class="language-xml"><DataGridTextColumn Binding="{Binding Name}"> <DataGridTextColumn.CellStyle> <Style TargetType="DataGridCell"> <Style.Triggers> <Trigger Property="Text" Value="John"> <Setter Property="Background" Value="LightGreen"/> </Trigger> </Style.Triggers> </Style> </DataGridTextColumn.CellStyle> </DataGridTextColumn></code>
或者,您可以使用 ValueConverter 將值對應到顏色,從而靈活地定義配色方案。這是一個範例:
<code class="language-csharp">public class NameToBrushConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { string input = (string)value; switch (input) { case "John": return Brushes.LightGreen; // 添加更多情况 default: return DependencyProperty.UnsetValue; } } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotSupportedException(); } }</code>
ValueConverter 的用法:
<code class="language-xml"><DataGridTextColumn Binding="{Binding Name}"> <DataGridTextColumn.CellStyle> <Setter Property="Background" Value="{Binding Name, Converter={StaticResource NameToBrushConverter}}"/> </DataGridTextColumn.CellStyle> </DataGridTextColumn></code>
最後,第三種方法可讓您直接將儲存格的背景綁定到傳回對應顏色的屬性。透過實作 INotifyPropertyChanged 接口,可以引發屬性更改,從而觸發使用者介面中的更新。
以上是如何根據儲存格值有條件地變更 WPF DataGrid 儲存格背景顏色?的詳細內容。更多資訊請關注PHP中文網其他相關文章!