带有DataTemplates的WPF ListBoxItems - 如何从DataTemplate中引用绑定到ListBoxItem的CLR对象?

Joh*_*nan 9 wpf listbox datatemplate listboxitem

我有一个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}"/>
Run Code Online (Sandbox Code Playgroud)

C#:

private void DeleteButton_Click(object sender, RoutedEventArgs e)
{
    Console.WriteLine("Where mah ListBoxItem?");
}
Run Code Online (Sandbox Code Playgroud)

ben*_*wey 12

一般来说人们会对直接绑定到的CLR对象感兴趣ListBoxItem,而不是实际的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}"/>
Run Code Online (Sandbox Code Playgroud)

在您的代码隐藏,你ButtonDataContext是等于你DataTemplateDataContext.在这种情况下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);
}
Run Code Online (Sandbox Code Playgroud)