[英]WPF DataGrid cell slyle change after update
我有一個帶有動態生成的列的DataGrid,我需要更改一些操作后其值已更改的單元格樣式。
DataGrid的ItemsSource定義為List<MyTableRow>
,其中
public class MyTableRow
{
private string[] _values;
private string _rowHeader;
// getters and setters here
}
DataGrid列使用以下代碼生成:
for (int i = 0; i < source[0].Values.Length; i++)
{
var col = new DataGridTextColumn();
var binding = new Binding("Values[" + i + "]");
col.Binding = binding;
col.CanUserSort = false;
this.dataGrid.Columns.Add(col);
this.dataGrid.Columns[i].Header = columnNames[i];
}
結果數據網格如下所示
當我嘗試突出顯示ItemsSource中的值已更改的單元格(粗體或彩色背景)時,就會出現問題。 這是我的問題分為兩部分的觀點:
ObservableColletion
或其他) 我嘗試使用xaml樣式和/或觸發器來執行此操作,但事實證明我不知道應該將什么值盲目傳遞給轉換器
<Style TargetType="TextBlock">
<Setter Property="Background"
Value="{Binding <!-- some proper binding here -->,
Converter={StaticResource ValueToBrushConverter}}"/>
</Style>
在SO上找到的其他解決方案要么具有綁定的相同“問題”,要么就是行不通。 如何突出顯示一個單元格而不是整個行/列? 如果需要,我可以更改ItemsSource, MyTableRow
字段和/或列的生成代碼
有人可以幫我嗎? 自從我堅持這個問題以來已經過了幾天
UPDATE找到解決方案
最后找出如何做我想做的。 解決方案有點“骯臟”,但對我來說很好。 我在需要突出顯示的每個單元格中添加了不間斷的空格字符
private const string NBSP = "\ "
之后要做的就是創建價值轉換器。 所以我在XAML中添加了MultiBinding
:
<DataGrid.CellStyle>
<Style TargetType="{x:Type DataGridCell}">
<Setter Property="Background">
<Setter.Value>
<MultiBinding Converter="{StaticResource ValueToBrushMultiConverter}" >
<MultiBinding.Bindings>
<Binding RelativeSource="{RelativeSource Self}" />
<Binding RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType={x:Type DataGridRow}}" />
</MultiBinding.Bindings>
</MultiBinding
</Setter.Value>
</Setter>
</Style>
</DataGrid.CellStyle>
onverter定義為:
public class ValueToBrushMultiConverter : IMultiValueConverter
{
private const string NBSP = "\u00A0";
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var cell = (DataGridCell)values[0];
var dgRow = (DataGridRow)values[1];
var test = (dgRow.Item as TableRow<string, string>).Values[cell.Column.DisplayIndex];
if (test.Contains(NBSP))
return System.Windows.Media.Brushes.PaleGreen;
return DependencyProperty.UnsetValue;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
}
希望這對某人有幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.