0
votes

I have assigned ItemsSource property of first ListBox 'ListBox1' as the ItemsSource of another ListBox namely 'ListBox2' . If I set ListBox2's ItemsSource as null, then I am unable to add any Items further to ListBox1's ItemsSource.

Below is the xaml snippet,

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

In Code behind, I set the ItemSource of ListBox2 as null on button click like below,

        ListBox2.SetCurrentValue(ListBox.ItemsSourceProperty, null);

Once this is done, I tried to add Items to ListBox1's "Coll" collection, but throws NRE that "Coll" is null.

Any suggestions plz.

Regards, Dinesh Kumar P

1
Why not just set the ItemsSource of ListBox2 to Coll? - paparazzo

1 Answers

0
votes

The two-way binding on ListBox2.ItemsSource sets ListBox1.ItemsSource to null when ListBox2.ItemsSource is set to null. Subsequently, the two-way binding on ListBox1.ItemsSource also sets Coll to null.

Don't make the ItemsSource bindings two-way. It is not necessary, and collection changes will still be notified.

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

It's not really clear what you are going to achieve, but it may be better to also bind ListBox2.ItemsSource directly to the Coll property.