我有以下xaml:
<ItemsControl>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Content="{Binding Name}"></Button>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
在我的代码中,我有一个事件让我可以访问该按钮。如何获取按钮对象并获取其名称绑定的对象?
这是我想要工作的psudo代码:
public void MyEvent(Object obj)
{
Button myButton = (Button) obj;
MyBoundClass myObject = GetBoundClassFromProperty(myButton.Name);
// Do something with myObject.
}
答案 0 :(得分:17)
尝试访问DataContext属性。这将包含对按钮绑定的当前项的引用。
public void MyEvent(Object obj)
{
Button myButton = (Button) obj;
MyBoundClass myObject = myButton.DataContext as MyBoundClass;
// Do something with myObject.
}