我有这个 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>
和
ObservableCollection<Name>
在我的代码隐藏中绑定(bind)到 ListView 的称为“名称”。将新名称添加到集合中时,我希望 ListView 更改该新添加名称的背景颜色。我该怎么做呢?
最佳答案
您可以在 listbox.Items 属性上订阅 ItemsChanged 事件。这有点棘手,因为您必须先施放它。订阅的代码如下所示:
((INotifyCollectionChanged)MainListBox.Items).CollectionChanged += ListBox_CollectionChanged;
然后在该事件中,您可以使用如下代码访问您的项目:
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);
}
}
关于wpf - 将项目添加到 ListView 时触发的事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5904519/