C# 如何访问父级';数据上下文
如何访问父级的DataContext 我有一个包含3个按钮的UserControl,我想将其用于几个不同的UserControl,因此用户总是可以使用相同的操作 单击“添加”按钮时,我需要在当前DataContext中执行一些操作,这并不麻烦,因为我可以执行以下操作:C# 如何访问父级';数据上下文,c#,wpf,xaml,C#,Wpf,Xaml,如何访问父级的DataContext 我有一个包含3个按钮的UserControl,我想将其用于几个不同的UserControl,因此用户总是可以使用相同的操作 单击“添加”按钮时,我需要在当前DataContext中执行一些操作,这并不麻烦,因为我可以执行以下操作: public void CtrlClicked(object sender, RoutedEventArgs e){ Button btn = sender as Button; MyClass2 c2 = btn
public void CtrlClicked(object sender, RoutedEventArgs e){
Button btn = sender as Button;
MyClass2 c2 = btn.DataContext as MyClass2;
c2.CallCustomMethod();
}
单击按钮“Del”时,我想从保存在MyClass1
中的列表中删除对象MyClass2
。
为了做到这一点,我需要访问MyClass1
我的UI(伪代码):
那么我怎样才能访问MyClass1对象呢
我发现我可以使用.Parent
在树上行走,但只能做到某一点:
Grid gScheduleControlBar = btn.Parent as Grid;
UserControl ucScheduleControlBar = gScheduleControlBar.Parent as UserControl;
Grid gDay = ucScheduleControlBar.Parent as Grid;
UserControl ucDay = gDay.Parent as UserControl;
//ucDay.Name confirms it's the userControl defined
Grid grid = ucDay.Parent as Grid;
// grid.Name="" and grid.Parent = null
因此,从这里没有进一步向上的方法,这意味着我不能通过UserControl
“border”
有什么想法吗?
作为回退选项,当然有在MyClass2
中存储MyClass1
引用的方法
编辑=>最终结果:
如果您想通过绑定实现这一点,您可以使用相对资源={RelativeSource Mode=FindAncestor-anstortype=yourNamespace:YourType}
,从代码中您可以使用VisualTreeHelper
获取任何控件的可视父控件
如果层次结构中存在该类型的多个父级,则可以另外指定一个AncestorLevel
。在您包含的示例中,它看起来像是antestortype=UserControl
和antestorlevel=2
应该可以工作。如果您想通过绑定实现这一点,可以使用RelativeSource={RelativeSource Mode=FindAncestor-antestortype=where}
,从代码中,您可以使用VisualTreeHelper
来获取任何控件的可视父控件。@ManfredRadlwimmer完全同意您的看法,这是可行的,但仅在ancestorType始终相同的场景中才行。因此,这将限制我对“UserControl ucButton”的使用,因为它只能在UserControl(antestortype)
存在的地方使用。有没有没有不受限制的想法?如果你希望每个案例都有相同的解决方案,那么有些东西必须保持不变。例如,如果您知道每次都要获取父级的父级,则可以使用AncestorType=FrameworkElement
并指定AncestorLevel
来指示层次结构中较高的元素。但是,您必须考虑自动生成的ContentPresenter。在您问题中包含的示例中,它看起来像是antestortype=UserControl
和antestorlevel=2
应该可以工作。@ManfredRadlwimmer aah…我想我需要直接按名称指定我的UserControl
,而不是像UserControl
那样宽泛。工作完美无瑕。你能帮我把这个问题转化成一个答案吗?当然,给我一分钟
Grid gScheduleControlBar = btn.Parent as Grid;
UserControl ucScheduleControlBar = gScheduleControlBar.Parent as UserControl;
Grid gDay = ucScheduleControlBar.Parent as Grid;
UserControl ucDay = gDay.Parent as UserControl;
//ucDay.Name confirms it's the userControl defined
Grid grid = ucDay.Parent as Grid;
// grid.Name="" and grid.Parent = null