0
votes

I have a user control containing an expander. The content of the explander is a ListBox bound to an object, and a DataTemplate displays it correctly. The problem is this: the user can select a Listbox item, and the SelectionChanged handler changed the DataContext of the ListBox to the selected object.

Like this:

<ListBox 
    Name="RelativesLB" ItemsSource="{Binding Relatives}", 
    ItemsTemplate ="{...}",
    Selectionchanged="Relatives_OnSelectionChanged" />

And:

Relatives_OnSelectionChanged(object sender, ...EventArgs e)
{
    var who = (sender as ListBox).SelectedItem as Person;
    if (who == null)
        return;

    People.DataContext = who;

Here is the problem:

  1. The SelectionChanged event fires.
  2. The DataContext is changed, and the ListBox repopulates.
  3. The SelectionChanged event fires with SelectedItem = null. Here, my code does not change the DataContext; it just returns.
  4. the SelectionChanged event fires again with SelectedItem = <whatever is first>. Here, my code changes the DataContext again to that item I don't want this bit. Actually, I want to stop after 2.
  5. the Datacontext is changed to <whatever is first>

  6. ...
    and so on, until we get an empty Person.Relatives, then we stop.

What I want is the stop after the first DataContext change. You select a person from the Relatives collection, and get the view for that person.

How can I stop the subsequent SelectionChanged events firing?

1

1 Answers

0
votes

I guess, in your on Relatives_OnSelectionChanged you need to set

e.Handled = True;