【发布时间】:2010-10-20 10:35:26
【问题描述】:
我有一个 ListBox,它绑定到 ObservableCollection。
每个ListBoxItem 都以DataTemplate 显示。我的DataTemplate 中有一个按钮,单击该按钮时需要引用ObservableCollection 的成员,它是DataTemplate 的一部分。我无法使用ListBox.SelectedItem 属性,因为单击按钮时该项目没有被选中。
所以要么:我需要弄清楚如何在鼠标悬停或单击按钮时正确设置ListBox.SelectedItem。或者我需要找出另一种方法来获取对绑定到按钮所属 ListBoxItem 的 CLR 对象的引用。第二个选项看起来更干净,但任何一种方式都可能没问题。
下面的简化代码段:
XAML:
<DataTemplate x:Key="postBody">
<Grid>
<TextBlock Text="{Binding Path=author}"/>
<Button Click="DeleteButton_Click">Delete</Button>
</Grid>
</DataTemplate>
<ListBox ItemTemplate="{StaticResource postBody}"/>
C#:
private void DeleteButton_Click(object sender, RoutedEventArgs e)
{
Console.WriteLine("Where mah ListBoxItem?");
}
【问题讨论】:
标签: wpf listbox datatemplate listboxitem