我有一个 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/