默認情況下,DataGrid
使用虛擬化來提高性能 - 它實例DataGridRow
只爲ItemsSource
當前可見的項目,它創造(或回收)更需要(例如,當用戶改變窗口大小或滾動)。
要立即解決的問題,你可以做這樣的事情:
public UserControl1()
{
InitializeComponent();
...
DataGrid1.LoadingRow += DataGrid1_LoadingRow;
}
Dictionary<int, Style> rowStyles = new Dictionary<int, Style>();
void DataGrid1_LoadingRow(object sender, DataGridRowEventArgs e)
{
int rowIndex = DataGrid1.Items.IndexOf(e.Row.Item);
if (rowStyles.ContainsKey(rowIndex))
{
e.Row.Style = rowStyles[rowIndex];
}
else
{
e.Row.Style = null;
}
}
void ColorPicker_SelectedColorChanged(object sender, RoutedPropertyChangedEventArgs<Color> e)
{
Style style = new Style(typeof(DataGridRow));
style.Setters.Add(new Setter(Control.BackgroundProperty, new SolidColorBrush(e.NewValue)));
foreach (object selectedItem in DataGrid1.SelectedItems)
{
int rowIndex = DataGrid1.Items.IndexOf(selectedItem);
rowStyles[rowIndex] = style;
}
DataGrid1.Items.Refresh();
}
不過,我會建議對MVVM和WPF動態造型閱讀起來,而不是通過修改視圖中直接綁定視圖模型和只修改模型:
- 擴展您的數據模型,以包含新的樣式屬性
- 綁定DataGridRow.Style到模型的樣式屬性
- 當用戶選擇一個顏色,修改適當的模型式
例如:
<DataGrid Name="DataGrid1">
<DataGrid.RowStyle>
<Style TargetType="{x:Type DataGridRow}">
<Setter Property="Background" Value="{Binding rowBackground}"/>
</Style>
</DataGrid.RowStyle>
</DataGrid>
DataTable Model { get; set; }
public UserControl1()
{
InitializeComponent();
this.Model = new DataTable() { Locale = CultureInfo.CurrentCulture };
this.Model.Columns.Add("a", typeof(int));
this.Model.Columns.Add("b", typeof(string));
this.Model.Columns.Add("rowBackground", typeof(Brush));
this.Model.Rows.Add(1, "one", Brushes.White);
this.Model.Rows.Add(2, "two", Brushes.White);
this.Model.Rows.Add(3, "three", Brushes.White);
this.Model.AcceptChanges();
DataGrid1.ItemsSource = this.Model.DefaultView;
}
void ColorPicker_SelectedColorChanged(object sender, RoutedPropertyChangedEventArgs<Color> e)
{
Brush brush = new SolidColorBrush(e.NewValue);
foreach (DataRowView selectedItem in DataGrid1.SelectedItems)
{
selectedItem["rowBackground"] = brush;
}
}
[杜尚](http://stackoverflow.com/users/400470/dusan),非常感謝。第一種解決方案工作,但不是很好 - 在對索引進行排序索引移動和行的顏色後,索引1將移動到表中的第一行(可能是11行或5行 - 取決於排序結果)。但第二種解決方案運行良好,理想適合我的應用程序的體系結構。我認爲這是我學習MVVM模式的時間:) –