0

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?

PScr
  • 449
  • 2
  • 11

1 Answers1

0

I guess, in your on Relatives_OnSelectionChanged you need to set

e.Handled = True;
Muds
  • 4,006
  • 5
  • 31
  • 53
  • Thanks, I'll try it, but I don't see it preventing new events firing when the selection is changed. – PScr Sep 16 '15 at 08:21
  • Muds, I tried it and it made no difference. I think it is for two reasons. – PScr Sep 16 '15 at 20:41
  • ... two reasons. Firstly, nothing else is interesting in the `SelectionChanged` event. I don't see why I should not stop it bubbling, though. Secondly, there is a hew `event` when the `DataContext` changes and the `ListBox`is repopulated. I get an `event` when the that happens, and there is nothing selected (`SelectedItem == null`). Then, the first Item gets selected, if there is one, and `SelectionChanged` fires again (and with my code, the `DataContext` changes to that first Item, and on we go. Until we get to an empty `ListBox`. – PScr Sep 16 '15 at 20:47