在为Observable Collection
设置数据绑定时,在以下上下文中:在XAML中使用WPF实现CollectionChanged处理程序,所有绑定都正常工作,但我发现除了在ListBox中更改ItemsSource定义的属性外,我还必须手动更新UI的可视化容器,代码类似于:
<Grid DataContext="{Binding ElementName=PollPublicStockMainWindow}">
<ListBox Height="132" HorizontalAlignment="Left" Name="lbFiles"
VerticalAlignment="Top" Width="167"
Margin="{StaticResource ConsistemtMargins}"
ItemsSource="{Binding LbItems}">
<ListBox.InputBindings>
<KeyBinding Key="Delete" Command="local:MainWindow.DeleteEntry"/>
</ListBox.InputBindings>
</ListBox>
</Grid>
后台代码:public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
LbItems = new ObservableCollection<string>();
LbItems.CollectionChanged += lbFiles_CollectionChanged;
}
private void lbFiles_CollectionChanged(object sender,
System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
MemoryPersistentStorageBridge memBridge = GetPersistentStorageBridge;
List<string> newFileList = new List<string>();
foreach (string str in LbItems) {
DoSomethingWithNewString(str); //these 2 lines are always paired?
lbFiles.Items.Add(str); // this should NOT be needed
}
}
}
我错过了一个绑定吗?
设置LbItems
时是否触发PropertyChanged
?看起来不是这样的。在构造函数中,首先调用InitializeComponent
,然后在LbItems = new ObservableCollection<string>();
中初始化集合。我认为你的集合初始化"太晚"了,因为绑定已经被处理过了。如果在设置LbItems
时不触发更改的属性,则绑定将不会更新为实际绑定到集合。