WPF ListBoxItems with DataTemplates-如何从DataTemplate中引用绑定到ListBoxItem的CLR对象?
我有一个列表框,它绑定到一个WPF ListBoxItems with DataTemplates-如何从DataTemplate中引用绑定到ListBoxItem的CLR对象?,wpf,listbox,datatemplate,listboxitem,Wpf,Listbox,Datatemplate,Listboxitem,我有一个列表框,它绑定到一个可观察集合 每个ListBoxItem都显示有DataTemplate。我的DataTemplate中有一个按钮,单击该按钮时,需要引用observedcollection的成员,该成员是的数据模板的一部分。我无法使用列表框。SelectedItem属性,因为单击按钮时该项未被选中 因此:我需要弄清楚如何正确设置列表框。当鼠标悬停或单击按钮时,选择editem。或者我需要找到另一种方法来获取对绑定到按钮所属的ListBoxItem的CLR对象的引用。第二种选择似乎更为
可观察集合
每个ListBoxItem
都显示有DataTemplate
。我的DataTemplate
中有一个按钮,单击该按钮时,需要引用observedcollection
的成员,该成员是的数据模板的一部分。我无法使用列表框。SelectedItem
属性,因为单击按钮时该项未被选中
因此:我需要弄清楚如何正确设置列表框。当鼠标悬停或单击按钮时,选择editem
。或者我需要找到另一种方法来获取对绑定到按钮所属的ListBoxItem
的CLR对象的引用。第二种选择似乎更为简洁,但两种方法都可以
简化代码段如下:
XAML:
一般来说,人们会对直接绑定到
ListBoxItem
的CLR对象感兴趣,而不是实际的ListBoxItem
。例如,如果您有一个帖子列表,您可以使用现有的模板:
<DataTemplate x:Key="postBody" TargetType="{x:Type Post}">
<Grid>
<TextBlock Text="{Binding Path=author}"/>
<Button Click="DeleteButton_Click">Delete</Button>
</Grid>
</DataTemplate>
<ListBox ItemTemplate="{StaticResource postBody}"
ItemSource="{Binding Posts}"/>
根据需要做什么,您有几种可能性 首先,主要问题是:“你为什么需要这个?”?大多数情况下,引用容器项目没有实际用途(不是说这是您的情况,但您应该详细说明)。如果您正在对列表框进行数据绑定,则很少有这种情况 其次,您可以使用
myListBox.ItemContainerGenerator.ContainerFromItem()
从列表框中获取项目,前提是您的列表框名为myListBox
。从sender参数中,您可以取回模板化的实际项目,例如(其中XXX
是您的数据绑定数据类型):
Container=发送方作为框架元素;
if(发送方!=null)
{
MyItem=Container.DataContext作为XXX;
MyElement=MyListBox.ItemContainerGenerator.ContainerFromItem(MyItem);//这太完美了,你也设法修正了我问题的措辞。我会编辑它,因为你是对的,我对绑定的CLR对象感兴趣,而不是ListBoxItem本身。这是对问题最初措辞的很好回答。Bendwey正确地认为我说的话不是真的,但这也是值得赞赏的。投了赞成票。
private void DeleteButton_Click(object sender, RoutedEventArgs e)
{
Console.WriteLine("Where mah ListBoxItem?");
}
<DataTemplate x:Key="postBody" TargetType="{x:Type Post}">
<Grid>
<TextBlock Text="{Binding Path=author}"/>
<Button Click="DeleteButton_Click">Delete</Button>
</Grid>
</DataTemplate>
<ListBox ItemTemplate="{StaticResource postBody}"
ItemSource="{Binding Posts}"/>
private void DeleteButton_Click(object sender, RoutedEventArgs e){
var post = ((Button)sender).DataContext as Post;
if (post == null)
throw new InvalidOperationException("Invalid DataContext");
Console.WriteLine(post.author);
}
Container = sender as FrameworkElement;
if(sender != null)
{
MyItem = Container.DataContext as XXX;
MyElement = MyListBox.ItemContainerGenerator.ContainerFromItem(MyItem); // <-- this is your ListboxItem.
}