2
votes

I'm trying to use a SourceUpdated event in ListBox, but it doesn't fire. I have binded ObservableCollection to ItemSource of ListBox, set NotifyOnSourceUpdated = true, and binding is working correctly - after adding new item to the collection, the ListBox displays new item, but without fireing the event.

MainWindow.xaml.cs:

public partial class MainWindow:Window
{
    public ObservableCollection<string> Collection { get; set; }

    public MainWindow()
    {
        InitializeComponent();
        Collection = new ObservableCollection<string>();
        var custBinding = new Binding()
        {
            Source = Collection,
            NotifyOnSourceUpdated = true
        };
        intList.SourceUpdated += intList_SourceUpdated;
        intList.SetBinding(ItemsControl.ItemsSourceProperty, custBinding);
    }

    private void intList_SourceUpdated(object sender, DataTransferEventArgs e)
    {
        MessageBox.Show("Updated!");
    }

    private void btnAddInt_Click(object sender, RoutedEventArgs e)
    {
        var randInt = new Random().Next();
        Collection.Add(randInt.ToString());
    }
}

MainWindow.xaml:

<Window x:Class="Test.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:Test"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800">
<Grid>
    <Button x:Name="btnAddInt" Content="Button" HorizontalAlignment="Left" Margin="41,31,0,0" VerticalAlignment="Top" Width="75" Click="btnAddInt_Click"/>
    <ListBox x:Name="intList" HorizontalAlignment="Left" Height="313" Margin="160,31,0,0" VerticalAlignment="Top" Width="600"/>

</Grid>

What am I missing, that it's not working ? Thank you for an advice.

1

1 Answers

3
votes

SourceUpdated is only fired on elements that can accept input and change the databound source value directly.

https://msdn.microsoft.com/en-us/library/system.windows.data.binding.sourceupdated(v=vs.110).aspx

In this case, the listbox itself is not updating the collection, rather the collection is being updated via a button click. This has nothing to do with the listbox firing the SourceUpdated Event.

Only input elements that can accept input like a textboxes, checkboxes, radio buttons and custom controls that use those controls will be able to two-way bind and transfer their values back to the source it is bound to.

You may be looking for CollectionChanged which will fire when items are added or removed from the Collection.

https://msdn.microsoft.com/en-us/library/ms653375(v=vs.110).aspx

Collection = new ObservableCollection<string>();
Collection.CollectionChanged += (s, e) =>
{
    // collection changed!
};

Hope this helps! Cheers!