1

在为 设置数据绑定时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>

代码隐藏:

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

我错过了绑定吗?

4

1 回答 1

3

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

于 2013-01-18T18:06:57.313 回答