ObservableCollection< T> WPF绑定显示未更新 [英] ObservableCollection<T> WPF Binding Display Not Updating

查看:84
本文介绍了ObservableCollection< T> WPF绑定显示未更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下情况下为 Observable Collection 设置数据绑定时:使用WPF在XAML中实现CollectionChanged处理程序,所有绑定均正常运行,但我发现除了更改ListBox中ItemsSource定义的属性外,我必须使用类似于以下代码的代码手动更新UI的可视容器:

In setting up data binding for Observable Collection , under the following context: Implementing CollectionChanged Handler in XAML with WPF all bindings are working correctly, but I'm finding that in addition to changing the Property defined by ItemsSource within the ListBox, I am having to manually update the UI's visual container with code similar to:

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:

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

我缺少约束力吗?

推荐答案

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

Do you fire PropertyChanged when LbItems is set? It does not look that way. In the constructor, you call InitializeComponent first and then initialize the collection in LbItems = new ObservableCollection<string>();. I think that your collection is initialized "too late", because the binding will already have been processed. If you do not fire a property changed when LbItems is set then the binding will not be updated to actually bind to the collection.

这篇关于ObservableCollection&lt; T&gt; WPF绑定显示未更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆