【发布时间】:2012-11-11 00:04:50
【问题描述】:
我想动态更改 ListView 的项目背景,所以我使用 Timer 作为事件触发器。但是在定时器被触发后,背景颜色无法自动刷新,直到我调整窗口大小。这是我的代码 sn-p:
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;
}
};
}
【问题讨论】: