我有一個填充了一些視圖模型類的觀察集合一個ItemsControl,就像這樣:獲取項目在ItemsControl中
<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?
}
啊挺好的。這顯然會比我列出的方法更好,但只適用於非默認數據上下文非常複雜的模板。 – 2011-03-23 03:20:49
@ A.R.:確切地說。 – Jon 2011-03-23 03:22:39
這可能很愚蠢,但你能結合我的答案和你的?他們在某種意義上都是「正確的」,我想給你一個綠色檢查,因爲你的檢查更加完整。我認爲其他人可以從兩種方法中受益,取決於他們在做什麼。 – 2011-03-23 12:26:11