views:

319

answers:

2

I have a ListView in my WPF UserControl using an ItemTemplate to display the items. Within the template is a button. When I select one item and then click on the button of another item, the previously selected item is still selected. I wonder how to automatically select the item the button is in when the button is clicked.

Xaml

<UserControl.Resources>
  <DataTemplate x:Key="ItemTemplate">
    <Border>
      <Grid>
        <!-- lots of stuff go here -->
        <Button Click="MyButton_Click">Clickme</Button>
      </Grid>
    </Border>
  </DataTemplate>
</UserControl.Resources>

<ListView x:Name="_listView"
  ItemTemplate="{StaticResource ItemTemplate}">
</ListView>

C# Code behind

void MyButton_Click(object sender, RoutedEventArgs e)
{
  MessageBox.Show( string.Format( "clicked on {0}",  
    this._listView.SelectedItem.ToString() ) ) ;
}
A: 

When you press the button your click / mouse down event is handled by the button and therefore does not route through to the ListView control.

A possible way to solve this is to manually set the listview.SelectedItem in the button click event.

Lozzey
A: 

I would do it by getting the data context of the sender object. Assuming your listview is a list of objects of type MyObject... then something like this would allow you to reference the selected object.

    void MyButton_Click(object sender, RoutedEventArgs e) 
    {
        Button b = sender as Button;
        if (b == null)
        {
            return;
        }

        MyObject o = b.DataContext as MyObject;
        if (o != null)
        {
            // Put stuff for my object here
        }                                    
    }
Mark Pearl
Thanks Mark. The solution you posted is exactly what I was looking for. I added "_listView.SelectedItem = o" and everything now works as intended.
miasbeck
Awesome.. great to help!
Mark Pearl