I want change the ListView’s item background dynamicly, so I using the Timer as the event trigger. But after the timer is triggered, the background color can not refresh automatically until I resize the window. Here is my code snippet:
public MainWindow()
{
InitializeComponent();
ObservableCollection<Object> People = new ObservableCollection<Object>();
for (int i = 0; i < 10; i++)
People.Add(new Person());
listView.ItemsSource = People;
System.Timers.Timer _timer = new System.Timers.Timer(10);
_timer.Elapsed += new System.Timers.ElapsedEventHandler(theObjectDroped);
_timer.AutoReset = true;
_timer.Enabled = true;
}
public void theObjectDroped(object source, System.Timers.ElapsedEventArgs e)
{
for (int i = 0; i < listView.Items.Count; i++)
{
Dispatcher.Invoke(new Action<int, Brush>(ModifyListViewBackground), i, Brushes.Red);
}
}
private void ModifyListViewBackground(int i, Brush brush)
{
listView.ItemContainerGenerator.StatusChanged += (s, e) =>
{
ListViewItem row = listView.ItemContainerGenerator.ContainerFromIndex(i) as ListViewItem;
if (row != null && row.Background != brush)
{
row.Background = brush;
}
};
}
In this line you are setting up a event handler for the StatusChanged event:
This gets fired when you do something like change the size of the window, which is why you only see the background colour change when you do something like resize the window.
To make it work as soon as the timer event gets fired, just remove the event handler in your
ModifyListViewBackgroundmethod:N.B. your timer is set up to trigger after 10ms. This is very fast, when trying this it was almost instantaneous. I set it to 1s (1000ms) so as I could see the event triggering after the timeout.