Selecting listbox item inside datatemplate
I have a listbox that uses a data template. The template is very simple and consists of an Image and a Te开发者_StackOverflowxtBlock. They are both bound to an XML document. The template is as follows:
<Window.Resources>
<XmlDataProvider x:Key="NinjaData" Source="\Data\Ninjas.xml" XPath="/Ninjas"/>
<DataTemplate x:Key="NinjaDataTemplate">
<StackPanel>
<StackPanel Orientation="Horizontal" Margin="0">
<Image Source="{Binding XPath=ImageFile}" Margin="5" Width="50"/>
<TextBlock Text="{Binding XPath=@Name}" Margin="5" FontFamily="OCR A Std" Foreground="#FF9114" FontSize="14" Name="NinjaName"/>
</StackPanel>
</StackPanel>
</DataTemplate>
</Window.Resources>
The Listbox is as follows:
<ListBox Background="{x:Null}" BorderBrush="{x:Null}"
ItemsSource="{Binding Source={StaticResource NinjaData}, XPath=Ninja}"
ItemTemplate="{StaticResource NinjaDataTemplate}"
>
<ListBox.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Gray"></SolidColorBrush>
</ListBox.Resources>
<ListBox.Effect>
<DropShadowEffect ShadowDepth="1" Color="#FF282828"/>
</ListBox.Effect>
</ListBox>
I'm having trouble working out how to retrieve the content of the TextBlock inside the data template when I click on it in the listbox. I want to display it in a label somewhere else on the page, but I can't work out how to access that textblock.
Can anyone help and point me in the right direction? I feel like I'm going round in circles at the moment.
Thanks for any help.
As you have a ListBox you can use the selection, just name the ListBox and bind to the SelectedItem:
<ListBox Name="lb" ... />
<Label DataContext="{Binding SelectedItem, ElementName=lb}"
Content="{Binding XPath=@Name}"/>
This does not retrieve the Text of the TextBlock in the template but gets it from the same source as the template. (You could actually target the TextBlock in the Template itself but i would not recommend it)
Add a MouseLeftButtonUp event handler to your textblock inside your datatemplate like :
<TextBlock Text="{Binding XPath=@Name}" Margin="5" FontFamily="OCR A Std" Foreground="#FF9114" FontSize="14" Name="NinjaName" MouseLeftButtonUp="TextBlock_MouseLeftButtonUp"/>
Now your TextBlock_MouseLeftButtonUp should look like:
private void TextBlock_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
TextBlock txt = sender as TextBlock;
}
And now do whatever you like to do with txt
精彩评论