我有以下 xaml:
<ItemsControl>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Content="{Binding Name}"></Button>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
在我的代码中,我有一个事件让我可以访问按钮。我如何获取按钮对象并获取其名称绑定(bind)到的对象?
这是我想要使用的伪代码:
public void MyEvent(Object obj)
{
Button myButton = (Button) obj;
MyBoundClass myObject = GetBoundClassFromProperty(myButton.Name);
// Do something with myObject.
}
最佳答案
尝试访问 DataContext 属性。这将包含对按钮绑定(bind)到的当前项目的引用。
public void MyEvent(Object obj)
{
Button myButton = (Button) obj;
MyBoundClass myObject = myButton.DataContext as MyBoundClass;
// Do something with myObject.
}
关于c# - 从控件获取绑定(bind)对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2174204/