I have quastion about DataGrid in WPF .NET 4.
Here is XAML code with DataGrid:
<DataGrid Name="m_DataGrid">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Path=Name}">
<DataGridTextColumn.CellStyle>
<Style TargetType="{x:Type DataGridCell}">
<Style.Triggers>
<Trigger Property="IsSelected" Value="True" >
<Setter Property="Background" Value="Gray" />
<Setter Property="Foreground" Value="White" />
<Setter Property="BorderBrush" Value="Gray" />
</Trigger>
<DataTrigger Binding="{Binding Path=IsRed}" Value="True">
<Setter Property="Foreground" Value="Red" />
</DataTrigger>
</Style.Triggers>
</Style>
</DataGridTextColumn.CellStyle>
</DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
And there are methods in window code:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
for (int i = 0; i < 100; i++)
{
m_DataGrid.Items.Add(new MyItem(string.Format("Item {0}", i)));
}
}
private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Space)
{
e.Handled = true;
((MyItem)m_DataGrid.SelectedItem).IsRed = !((MyItem)m_DataGrid.SelectedItem).IsRed;
m_DataGrid.SelectedIndex++;
m_DataGrid.Items.Refresh();
}
}
And here is MyItem class Code:
public class MyItem
{
public string Name { get; set; }
public bool IsRed { get; set; }
public MyItem(string _Name)
{
Name = _Name;
IsRed = false;
}
}
The problem is, that I must use method m_DataGrid.Items.Refresh(); to show items in red color. But when I have eg. 100 items this method is too slow. So when I hold down spacebar items are marked with red color very slowly. How to do this in better and more elegant way? How to change item color without Refresh method?
Thank you for your answers and tips.
Your class, MyItem should inherit from INotifyPropertyChanged, and the IsRed property declared as…
With this scheme, when your code changes IsRed to true, the subscribers will be notified and your grid will make the appropriate update. This will achieve the result you are looking for.
The ‘Refresh’ method of the DataGrid is inappropriate for changes to a property.