我正在尝试翻译此XAML代码:
<Binding Path="DataContext" RelativeSource="{RelativeSource AncestorType={x:Type UserControl}}" />
进入此C#代码:
var binding = new Binding("DataContext")
{
RelativeSource = new RelativeSource {AncestorType = typeof(UserControl)}
};
var value = PropertyPathHelper.GetValue(binding);
我的PropertyPathHelper的实现(从another thread修改)如下:
public static class PropertyPathHelper
{
public static object GetValue(Binding binding)
{
BindingOperations.SetBinding(_dummy, Dummy.ValueProperty, binding);
return _dummy.GetValue(Dummy.ValueProperty);
}
private static readonly Dummy _dummy = new Dummy();
private class Dummy : DependencyObject
{
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register("Value", typeof(object), typeof(Dummy), new UIPropertyMetadata(null));
}
}
要么我的Binding声明不正确,要么我的PropertyPathHelper实现不正确,但是我不知道哪个,因为在运行时,“ var value”显示为null。即使我将不存在的名称传递给Binding的构造函数。
如果我在XAML中进行绑定,则绑定工作正常,但是我have在后面的代码中进行绑定。如果不清楚,我试图获取该视图的第一个祖先的DataContext的实际value,类型为UserControl。
我在做什么错?
我发现了一种实现目标的优雅方法,而且确实有效。
首先,在我的视图的XAML中,添加了以下属性:
Tag="{Binding RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"
然后我发现我可以用后面的代码中的以下代码来抓住我所需要的东西:
var v = this.Tag as FrameworkElement;
var vm = v.DataContext as MyViewModel; //The ViewModel of the parent view, not the current one
谢谢您的提问,@ Clemens。通过回旋方式,您帮助我以不同的方式思考我的问题!