0

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

下面是 xaml 片段,

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

任何建议请。

问候, Dinesh Kumar P

4

1 回答 1

0

ListBox2.ItemsSource设置ListBox1.ItemsSourcenullwhen的双向绑定ListBox2.ItemsSource设置为null。随后,双向绑定 onListBox1.ItemsSource也设置Collnull

不要进行ItemsSource双向绑定。没有必要,集合更改仍会收到通知。

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

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

于 2013-08-13T10:33:13.980 回答