I have an ItemTemplate that contains a simple button. When I click this button I need a way to identify the row clicked to pull out the item bound to the listbox.
XAML
<ListBox Name="DemoBox" SelectionChanged="listBox_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Height="150">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="400"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid Height="120" Grid.Column="0">
<Grid.RowDefinitions>
<RowDefinition Height="60"/>
</Grid.RowDefinitions>
<TextBlock
Grid.Row="0"
Text="{Binding SomeObjProperty}"/>
</Grid>
<Grid Height="120" Grid.Column="1" Margin="0,-12,0,0">
<Button Click="ShowStuffOnMap_Click">
<Button.Background>
<ImageBrush ImageSource="images/arrow.png"/>
</Button.Background>
</Button>
</Grid>
开发者_StackOverflow社区 </Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
click handler
private void ShowStuffOnMap_Click(object sender, RoutedEventArgs e)
{
//sender is the button so ...
}
Thank you in advance
Why do you have Button with a click event inside a ListBox with a SelectionChanged event? This makes up for some scary UX, if they have different actions!
The normal approach is to have a databound ListBox, and then use the SelectionChanged event to read out the selected item.
private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var listBox = sender as ListBox;
var selectedItem = listBox.SelectedItem as MyDataBoundType;
if (selectedItem != null)
{
// do stuff
}
// if you use the ListBox for navigation, set the SelectedIndex to -1
// listBox.SelectedIndex = -1;
}
But if you really really want to do it, you need to use the Tag
property.
<Button Click="ShowStuffOnMap_Click" Tag="{Binding}">
And then in your event handler:
private void ShowStuffOnMap_Click(object sender, RoutedEventArgs e)
{
var button = sender as Button;
var selectedItem = button.Tag as MyDataBoundType;
}
But I still think your approach here is wrong, and stands for bad user experience, as the normal approach to a list is that the entire line in the list, is one-selection only.
The best way to do this is to have some unique identifier in the template itself. For example, you have a TextBlock
- give it a unique name, and when the button is pressed, search the secondary grid for the TextBlock
with the identifier and read its Text
property.
精彩评论