从 ItemsControl 中的模板获取项目 [英] Get item from template in ItemsControl

查看:38
本文介绍了从 ItemsControl 中的模板获取项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ItemsControl,其中填充了一些 ViewModel 类的可观察集合,如下所示:

I have an ItemsControl that is populated with an observable collection of some ViewModel classes, like so:

<ItemsControl ItemsSource="{Binding MyCollection}">
  <ItemsControl.ItemTemplate>
    <DataTemplate Type="{x:Type local:MyViewModel}">
      <Button Content="{Binding ActionName}" Click="ClickHandler"/>
    </DataTemplate>
  <ItemsControl.ItemTemplate>
</ItemsControl>

效果很好,看起来很棒,但我似乎无法弄清楚如何让ClickHandler"知道由数据模板表示的类MyViewModel".看!

Works great, looks great, but I can't seem to figure out how to get the "ClickHandler" to be aware of the class 'MyViewModel' that is represented by the data template. Behold!

private void ClickHandler(object sender, RoutedEventArgs e)
{
  // The 'sender' is the button that raised the event.  Great!
  // Now how do I figure out the class (MyViewModel) instance that goes with this button?
}

推荐答案

在这种特定情况下,您自己的答案将起作用.这是另一种技术,虽然复杂得多,但也适用于任何场景,无论其复杂程度如何:

Your own answer will do the trick in this specific case. Here's another technique which, while much more complicated, will also work on any scenario regardless of complexity:

sender(它是一个 Button)开始,使用 VisualTreeHelper.GetParent 直到找到 ContentPresenter.这是您为每个项目指定的 ItemTemplate 托管的 UIElement 类型.让我们将 ContentPresenter 放入变量 cp 中.(重要提示:如果您的 ItemsControl 是一个 ListBox,那么我们将寻找一个 ListBoxItem 而不是 ContentPresenter代码>等).

Starting from sender (which is a Button), use VisualTreeHelper.GetParent until you find a ContentPresenter. This is the type of UIElement that the ItemTemplate you specified is hosted into for each of your items. Let's put that ContentPresenter into the variable cp. (Important: if your ItemsControl were a ListBox, then instead of ContentPresenter we 'd look for a ListBoxItem, etc).

然后,调用 ItemsControl.ItemContainerGenerator.ItemFromContainer(cp).为此,您需要对特定的 ItemsControl 有一些引用,但这应该不难——例如,您可以给它一个 Name 并使用FrameworkElement.FindName 从您的视图本身.ItemFromContainer 方法将返回您的 ViewModel.

Then, call ItemsControl.ItemContainerGenerator.ItemFromContainer(cp). To do that, you will need to have some reference to the specific ItemsControl but this shouldn't be hard -- you can, for example, give it a Name and use FrameworkElement.FindName from your View itself. The ItemFromContainer method will return your ViewModel.

所有这些都是我从 博士 WPF.

All of this I learned from the stupidly useful and eye-opening posts of Dr. WPF.

这篇关于从 ItemsControl 中的模板获取项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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