Button within ListBox ItemTemplate not selecting item

Viewed 2448

I have a situation with a ListBox control. Inside the item template there is a button. When I click the button I want to selected item of said ListBox to change to the item the button is in. At the moment, I can change the selected item by clicking elsewhere within the item template, but that doesn't work if I select the button. To clarify that last sentence for a commenter, if one clicks in the item template that is not the button, the SelectedItem will change as expected. If you click on the button within the item template, the SelectedItem will not change.

Further information: I am using MVVM and the button has attached to it a command within a view model. Any solution would need to allow this to continue to work.

The ListBox is linked to ItemSource, and the SelectedItem of the ListBox is bound to a property in the view model.

If there's a set way to do this, I've so far been unable to find it.

I am using C# and Visual Studio 2010.

Thanks.

4 Answers

You can get the Listbox that is parent of the button using this function:

    Function GetParent(child As UIElement, parentType As Type) As UIElement
        If child Is Nothing Then Return Nothing
        Dim p = child
        Do
            p = TryCast(VisualTreeHelper.GetParent(p), UIElement)
            If p Is Nothing Then Return Nothing
            If p.GetType Is parentType Then Return p
        Loop
    End Function

This is the code that selects the item. Add it to the Click event of the button:

Private Sub Button_Click(sender As Object, e As RoutedEventArgs)
  Dim lst As ListBox = GetParent(sender, GetType(ListBox))
  lst.SelectedIndex = lst.Items.IndexOf(Me.DataContext)
End Sub

C# version:

  private void Button_Click(object sender, RoutedEventArgs e)
    {
        Button b = sender as Button;
        TListBoxItems data = b.DataContext as TListBoxItems;
        ListBox aLB = new ListBox();
        aLB = (ListBox)GetParent(sender, aLB.GetType());
        aLB.SelectedIndex = aLB.Items.IndexOf(data);
    }

    public object GetParent(object child, Type parentType)
    {
        if (child == null)
            return null/* TODO Change to default(_) if this is not a reference type */;
        var p = child;
        do
        {
            p = VisualTreeHelper.GetParent((UIElement)p) as UIElement;
            if (p == null)
                return null/* TODO Change to default(_) if this is not a reference type */;
            if (p.GetType() == parentType)
                return p;
        }
        while (true);
    }
Related