views:

266

answers:

1

Hi,

I have a ListBox bound to an ObservableCollection with an ItemTemplate that contains another ListBox. First of all, I tried to get the last selected item of all the listboxes (either the parent and the inner ones) from my MainWindowViewModel this way:

public object SelectedItem
{
    get { return this.selectedItem; }
    set 
    {
        this.selectedItem = value;
        base.NotifyPropertyChanged("SelectedItem");
    }
}

So, for example, in the DataTemplate of the items of the parent ListBox I've got this:

<ListBox ItemsSource="{Binding Tails}"
 SelectedItem="{Binding Path=DataContext.SelectedItem, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}"/>

The problem now, is that when I select an item from the parent ListBox and then an item from a child listbox, I get this:

http://i40.tinypic.com/j7bvig.jpg

As you can see, two items are selected at the same time. How can I solve that?

Thanks in advance.

A: 

I have already solved this issue by registering a ClassHandler for the SelectedEvent of the ListBox control.

I just added this in the constructor of my MainWindow class:

EventManager.RegisterClassHandler(typeof(ListBox),
            ListBox.SelectedEvent,
            new RoutedEventHandler(this.ListBox_OnSelected));

That way, my ListBox_OnSelected event handler will be called whenever a listbox is called, and before the event handlers of the control itself are called.

In the MainWindowViewModel I have a property called SelectedListBox that keeps track of which one is selected:

public System.Windows.Controls.ListBox SelectedListBox
{
    get { return this.selectedListBox; }
    set
    {
        if (this.selectedListBox != null)
        {
            this.selectedListBox.UnselectAll();
        }
        this.selectedListBox = value;
    }
}

Why not using a simple SelectionChanged event handler? Because in the above code, every time you unselect a listbox it raises again the same event, getting an infinite loop of events that fortunately WPF is able to stop.

quimbs