Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i get the itemsourcechanged event? Listbox

How can i get the itemsourcechangedevent in listbox?

For eg. the itemsource changes from null to ListA then to ListB

I know there is no such event. But is there any workaround for this?

Thanks in advance :)

like image 833
TCM Avatar asked Feb 25 '11 16:02

TCM


2 Answers

A commonly used (answered) approach is use the PropertyChangedTrigger from the Blend SDK. However I don't like recommending the use of other SDKs unless there is a clear indication the SDK is already in use.

I'll assume for the moment that its in code-behind that you want listen for a "ItemsSourceChanged" event. A technique you can use is to create a DependencyProperty in your UserControl and bind it to the ItemsSource of the control you want to listen to.

private static readonly DependencyProperty ItemsSourceWatcherProperty = 
    DependencyProperty.Register(
       "ItemsSourceWatcher",
       typeof(object),
       typeof(YourPageClass),
       new PropertyMetadata(null, OnItemsSourceWatcherPropertyChanged));

private static void OnItemsSourceWatcherPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    YourPageClass source = d As YourPageClass;
    if (source != null)
        source.OnItemsSourceWatcherPropertyChanged();  
}

private void OnItemsSourceWatcherPropertyChanged()
{
    // Your code here.
}

Now given that your ListBox has a name "myListBox" you can set up watching with:-

Binding b = new Binding("ItemsSource") { Source = myListBox };
SetBinding(ItemsSourceWatcherProperty, b);
like image 57
AnthonyWJones Avatar answered Sep 24 '22 19:09

AnthonyWJones


There is no ItemsSourceChanged event in Silverlight.

But, there is a workaround. Use RegisterForNotification() method mentioned in this article to register a property value change callback for ListBox's ItemsSource property.

like image 42
decyclone Avatar answered Sep 24 '22 19:09

decyclone