在设置Observable Collection
的数据绑定时,在以下上下文中:Implementing CollectionChanged Handler in XAML with WPF所有绑定都正常工作,但我发现除了更改ListBox中ItemsSource定义的属性外,我不得不使用类似于:
XAML:
<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>
CodeBehind:
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
}
}
}
我错过了绑定吗?
答案 0 :(得分:3)
设置PropertyChanged
时是否解雇LbItems
?看起来并不那样。在构造函数中,首先调用InitializeComponent
,然后在LbItems = new ObservableCollection<string>();
中初始化集合。我认为你的集合初始化“太晚了”,因为绑定已经被处理了。如果在设置LbItems
时未触发更改的属性,则绑定将不会更新为实际绑定到集合。