2013-01-18 86 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時未觸發更改的屬性,則綁定不會更新爲實際綁定到集合。

相關問題