2013-01-18 43 views
1

在设置Observable Collection的数据绑定时,在以下上下文中:Implementing CollectionChanged Handler in XAML with WPF所有绑定工作正常,但我发现除了更改ListBox中由ItemsSource定义的属性之外,我还是具有类似于代码手动更新UI的可视容器:ObservableCollection <T> WPF绑定显示不更新

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> 

代码隐藏:

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 
     } 
    } 
} 

我是否缺少绑定?

回答

3

LbItems被设置时,你会发火吗PropertyChanged?它看起来并不那样。在构造函数中,首先调用InitializeComponent,然后在LbItems = new ObservableCollection<string>();中初始化该集合。我认为你的收藏已经“太迟”初始化了,因为绑定已经被处理了。如果您在设置LbItems时未触发更改的属性,则绑定不会更新为实际绑定到集合。

相关问题