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

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

问题描述

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

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

每个ListBoxItemDataTemplate一起显示.我的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而不是实际的ListBoxItem的CLR对象感兴趣.例如,如果您有帖子列表,则可以使用以下现有模板:

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天全站免登陆