【问题标题】:In ListBox cannot add Items after ItemSource is set to null在 ListBox 中 ItemSource 设置为 null 后无法添加 Items
【发布时间】:2013-08-13 10:20:48
【问题描述】:

我已将第一个 ListBox 'ListBox1' 的 ItemsSource 属性分配为另一个 ListBox 的 ItemsSource ,即 'ListBox2' 。如果我将 ListBox2 的 ItemsSource 设置为 null,那么我无法将任何项目进一步添加到 ListBox1 的 ItemsSource。

下面是xaml sn-p,

         <ListBox VerticalAlignment="Top" HorizontalAlignment="Center" Width="150" Margin="0 25 0 0"
                 x:Name="ListBox1" ItemsSource="{Binding Coll,Mode=TwoWay}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding _Name}"/>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

        <ListBox VerticalAlignment="Top" HorizontalAlignment="Center" Width="150" Margin="0 25 0 0"
                 x:Name="ListBox2" ItemsSource="{Binding Path=ItemsSource,ElementName=ListBox1,Mode=TwoWay}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding _Name}"/>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

在后面的代码中,我在单击按钮时将 ListBox2 的 ItemSource 设置为 null,如下所示,

        ListBox2.SetCurrentValue(ListBox.ItemsSourceProperty, null);

完成此操作后,我尝试将项目添加到 ListBox1 的“Col”集合中,但会抛出“Col”为空的 NRE。

任何建议请。

问候, 迪内什·库马尔 P

【问题讨论】:

  • 为什么不把 ListBox2 的 ItemsSource 设置为 Coll?

标签: wpf silverlight listbox wpf-controls itemssource


【解决方案1】:

ListBox2.ItemsSource 设置为null 时,ListBox2.ItemsSource 上的双向绑定将ListBox1.ItemsSource 设置为null。随后,ListBox1.ItemsSource 上的双向绑定也将Coll 设置为null

不要使ItemsSource 绑定双向。不是必须的,集合变化还是会通知的。

<ListBox x:Name="ListBox1"
         ItemsSource="{Binding Coll}" ... >
    ...
</ListBox>
<ListBox x:Name="ListBox2"
         ItemsSource="{Binding Path=ItemsSource, ElementName=ListBox1}" ... >
    ...
</ListBox>

目前还不清楚您要实现什么,但最好也将ListBox2.ItemsSource 直接绑定到Coll 属性。

【讨论】:

  • 嗨 Clemens,如果没有双向绑定,集合更改会收到通知。但我的问题是在将 ListBox2.ItemsSource 设置为 null 后,当我在“Col”集合中添加项目时,集合“Col”更改仅在 ListBox1 中通知,而不在 ListBox2 中通知。
  • 当然不是你设置它为null。当您将 ListBox2.ItemsSource 设置为 null 时,您的意图到底是什么?
猜你喜欢
  • 1970-01-01
  • 2012-09-12
  • 1970-01-01
  • 2017-07-05
  • 1970-01-01
  • 1970-01-01
  • 2014-09-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多