c# - 从 ItemsControl 中的模板获取项目

标签 c# wpf templates xaml

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

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

效果很好,看起来很棒,但我似乎无法弄清楚如何让“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?
}

最佳答案

好吧,我几乎立即意识到这是“发件人”的“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);
}

关于c# - 从 ItemsControl 中的模板获取项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5400390/

相关文章:

c# - 如何仅获取图像最后一行的像素并将其显示在图片框中。 C#

c# - cleartool 在命令提示符和 C# 应用程序中的行为不同

c# - 使用 ArcGIS Runtime 本地服务器实现 MVVM

c# - 从 WPF C# 中的 For 循环调用用户定义的函数

c++ - C++ 表达式模板的教程和介绍

c# - WPF 中的 3d 矢量计算

c# - 使用 John Myczek 类的水印

wpf - 如何将 WPF 窗口大小设置为相对监视器屏幕的 25%

c++ - C++ 模板函数的行为

css - 如何从 Blogger 购物模板中删除页脚文本