带有 DataTemplates 的 WPF ListBoxItems - 如何从 DataTemplate 中引用绑定到 ListBoxItem 的 CLR 对象? [英] WPF ListBoxItems with DataTemplates - How do I reference the CLR Object bound to ListBoxItem from within the DataTemplate?

查看:22
本文介绍了带有 DataTemplates 的 WPF ListBoxItems - 如何从 DataTemplate 中引用绑定到 ListBoxItem 的 CLR 对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ListBox,它绑定到 ObservableCollection.

I have a ListBox, that's bound to an ObservableCollection.

每个 ListBoxItem 都与 DataTemplate 一起显示.我的 DataTemplate 中有一个按钮,单击该按钮需要引用 ObservableCollection 的成员,它是 DataTemplate 的一部分.我不能使用 ListBox.SelectedItem 属性,因为单击按钮时项目没有被选中.

Each ListBoxItem is displayed with a DataTemplate. I have a button in my DataTemplate, that when clicked, needs a reference to the member of the ObservableCollection it's part of the DataTemplate for. I can't use the ListBox.SelectedItem property because the item does not become selected when clicking the button.

所以要么:我需要弄清楚当鼠标悬停或单击按钮时如何正确设置 ListBox.SelectedItem.或者我需要找出另一种方法来获取对绑定到按钮所属的 ListBoxItem 的 CLR 对象的引用.第二个选项似乎更简洁,但任何一种方式都可能没问题.

So either: I need to figure out how to properly set ListBox.SelectedItem when the mouse hovers, or when the button is clicked. Or I need to figure out another way to get a reference to the CLR Object bound to the ListBoxItem that the button belongs to. The second option seems cleaner, but either way is probably OK.

下面的简化代码段:

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?");
}

推荐答案

一般来说人们会对直接绑定到 ListBoxItem 的 CLR 对象感兴趣,而不是实际的 ListBoxItem.例如,如果您有一个帖子列表,您可以使用您现有的模板:

Generally speaking people will be interested in a CLR object directly bound to the ListBoxItem, not the actual ListBoxItem. If you had a list of posts for example you could use your existing template of:

<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}"/>

在您的代码隐藏中,您的 ButtonDataContext 等于您的 DataTemplateDataContext.在这种情况下,Post.

and in your code-behind, your Button's DataContext is equal to your DataTemplate's DataContext. In this case a Post.

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);
}

这篇关于带有 DataTemplates 的 WPF ListBoxItems - 如何从 DataTemplate 中引用绑定到 ListBoxItem 的 CLR 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆