ObservableCollection< T> WPF绑定显示未更新

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.