【问题标题】:Getting the value of a WPF RelativeSource binding in codebehind在代码隐藏中获取 WPF RelativeSource 绑定的值
【发布时间】:2020-07-29 12:05:53
【问题描述】:

我正在尝试翻译此 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 中进行绑定,绑定可以正常工作,但我必须在代码隐藏中进行。如果不清楚,我正在尝试获取此视图的第一个祖先的 DataContext 的实际 ,它是 UserControl 类型。

我做错了什么?

【问题讨论】:

  • 当 Dummy 实例显然没有祖先 ot 类型 UserControl 时,这应该如何工作?请让我们知道您实际想要达到的目标。
  • 我正在尝试获取我的视图所属的视图的 DataContext 的值。我的视图继承自 RadTabItem(来自第三方提供商),并包含在另一个继承自 UserControl 的视图中。
  • 抱歉,这还不够详细。除此之外,DataContext 属性支持值继承,这意味着您的视图的 DataContext 等于其父元素的 DataContext,除非您明确覆盖它。

标签: c# wpf data-binding code-behind relativesource


【解决方案1】:

我找到了一种更优雅的方式来实现我的目标......而且它确实有效。

首先,在我看来的 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。以一种迂回的方式,你帮助我以不同的方式思考我的问题!

【讨论】:

  • 请注意,如果您不检查结果是否为 null,请不要使用 as 运算符。改用类型转换:var v = (FrameworkElement)Tag;
猜你喜欢
  • 2012-07-15
  • 1970-01-01
  • 2013-10-17
  • 1970-01-01
  • 1970-01-01
  • 2021-07-19
  • 1970-01-01
  • 2014-04-10
  • 1970-01-01
相关资源
最近更新 更多