ObservableCollection <t> WPF绑定显示未更新</t>

时间:2013-01-18 17:38:01

标签: wpf user-interface data-binding

在设置Observable Collection的数据绑定时,在以下上下文中:Implementing CollectionChanged Handler in XAML with WPF所有绑定都正常工作,但我发现除了更改ListBox中ItemsSource定义的属性外,我不得不使用类似于:

的代码手动更新UI的可视容器

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

我错过了绑定吗?

1 个答案:

答案 0 :(得分:3)

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

相关问题