从ItemsControl中的模板中获取项目

A.R*_*.R. 2 c# wpf xaml templates

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

<ItemsControl ItemsSource="{Binding MyCollection}">
  <ItemsControl.ItemTemplate>
    <DataTemplate Type="{x:Type local:MyViewModel}">
      <Button Content="{Binding ActionName}" Click="ClickHandler"/>
    </DataTemplate>
  <ItemsControl.ItemTemplate>
</ItemsControl>
Run Code Online (Sandbox Code Playgroud)

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

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?
}
Run Code Online (Sandbox Code Playgroud)

A.R*_*.R. 7

好吧,我几乎立即意识到它是'发送者'的'DataContext'.除非社区认为这个问题太明显,否则我会放弃这个.

private void ClickHandler(object sender, RoutedEventArgs e)
{
  // This is the item that you want.  Many assumptions about the types are made, but that is OK.
  MyViewModel model = ((sender as FrameworkElement).DataContext as MyViewModel);
}
Run Code Online (Sandbox Code Playgroud)