将项目添加到 ListView 时触发的事件? [英] Event fired when item is added to ListView?
问题描述
我有这个 XAML:
<ListView Name="NameListView"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
Grid.Column="1">
<ListView.View>
<GridView>
<GridViewColumn>
<GridViewColumn.DisplayMemberBinding>
<MultiBinding StringFormat="{}{0} {1}">
<Binding Path="First" />
<Binding Path="Last" />
</MultiBinding>
</GridViewColumn.DisplayMemberBinding>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
和一个名为names"的 ObservableCollection
绑定到我的代码隐藏中的 ListView.将新名称添加到集合中时,我希望 ListView 更改该新添加名称的背景颜色.我该怎么做?
and an ObservableCollection<Name>
called "names" binded to the ListView in my code-behind. When a new new name is added to the collection, I want the ListView to change the background color of that newly added name. How do I go about doing it?
推荐答案
您可以订阅 listbox.Items 属性上的 ItemsChanged 事件.这有点棘手,因为你必须先施放它.订阅代码如下所示:
You can subscribe to the ItemsChanged event on your listbox.Items property. This is a little tricky because you have to cast it first. The code to subscribe would look like this:
((INotifyCollectionChanged)MainListBox.Items).CollectionChanged += ListBox_CollectionChanged;
然后在该事件中,您可以使用如下代码访问您的项目:
And then inside that event you can get to your item with code like this:
private void ListBox_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.NewItems.Count > 0)
{
Dispatcher.BeginInvoke(() =>
{
var newListItem = MainListBox.ItemContainerGenerator.ContainerFromItem(e.NewItems[0]) as Control;
if (newListItem != null)
{
newListItem.Background = System.Windows.Media.Brushes.Red;
}
}, DispatcherPriority.SystemIdle);
}
}
这篇关于将项目添加到 ListView 时触发的事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!