locked
Listbox selection changed event not firing RRS feed

  • Question

  • I have a listbox which has a datatemplate with a button inside it. I am using MVVM and MVVM light. When I click the button inside the datatemplate is clicked the selection changed event doesn't fire which means the SelectedItem of the Listbox is always null. Is there anyway around this? From what I have read the button inside the template "traps" the event so it doesn't get passed up to the listbox. Cheers, Chris.

    Monday, June 6, 2011 12:02 PM

Answers

  • You can set the ListBox.SelectedItem with the Button.DataContext in the Button_Click event:

    private void Button_Click(object sender, RoutedEventArgs e)
            {         
                listBox1.SelectedItem = ((Button)sender).DataContext;
            }

    Monday, June 6, 2011 1:38 PM

All replies

  • ypu can use "interactivity:EventTrigger" and "interactions:ChangePropertyAction" to explicitly set your ViewModel's selected property.

    Monday, June 6, 2011 12:57 PM
  • You can set the ListBox.SelectedItem with the Button.DataContext in the Button_Click event:

    private void Button_Click(object sender, RoutedEventArgs e)
            {         
                listBox1.SelectedItem = ((Button)sender).DataContext;
            }

    Monday, June 6, 2011 1:38 PM
  • This works great. I know it's not "proper" MVVM but I spent 2 hours looking at this and haven't found a better way.

    Monday, June 6, 2011 1:57 PM
  • I know it's not "proper" MVVM

    No one says you should have 0 code in code behind if using MVVM. It is perfectly all right to put pure UI related code in code behind.

    Monday, June 6, 2011 2:27 PM
  • <!--Add "System.Windows.Interactivity.dll" and "Microsoft.Expression.Interactions.dll" to your project-->       
            <Button xmlns:interactivity="http://schemas.microsoft.com/expression/2010/interactivity"
                    xmlns:interactions="http://schemas.microsoft.com/expression/2010/interactions"
    Name="myBtn"
    ...>
                <interactivity:Interaction.Triggers>
                    <interactivity:EventTrigger EventName="Click">
                        <interactions:ChangePropertyAction TargetObject="{Binding ElementName=listBox1}" PropertyName="SelectedItem" Value="{Binding ElementName=myBtn, Path=DataContext}" />
                    </interactivity:EventTrigger>
                </interactivity:Interaction.Triggers>
            </Button>


    ...and no codebehind

    Monday, June 6, 2011 2:56 PM