依赖 属性 GetValue 在不同 class

Dependency Property GetValue in different class

所以我在使用依赖属性时遇到了一些问题。但实际上只有当我试图从不同的 class.

访问它们时

例如,我正在检查以 ping 服务器并定义相应的依赖关系 属性:

        public static DependencyProperty PingStateProperty =
        DependencyProperty.Register("PingState", typeof(bool),
        typeof(MainWindow));

    public bool PingState
    {
        get { return (bool)GetValue(PingStateProperty); }
        set
        {
            SetValue(PingStateProperty, value);
            PropertyChanged(this, new PropertyChangedEventArgs("PingState"));
        }
    }

现在我想从另一个 class(特别是用户控件)中的依赖项 属性 中获取值。所以我有另一个 class 试图获得这样的值:

    public void MethodInClass2()
    {
        bool ping = (bool)GetValue(MainWindow.PingStateProperty);

我做错了什么?让我烦恼的是:当我在同一个 class 中调用 GetValue 时它正在工作。它没有给我一个编译错误或类似的东西,它似乎只是没有传递正确的值(在定义了 DP 的 class 1 中,我可以检查该值并得到 "true"正如预期的那样,但是当我尝试在 class 2 中做同样的事情时,我每次都得到 "false"。

在这种情况下我需要附件 属性 吗?也对他们进行了一些尝试,但不幸的是无济于事。

问候

除非您之前设置过,否则无法获取该值。如果目标对象是相同类型或派生对象,则只能设置该值,除非它是附加的 属性。像这样调用 GetValue not 从主 window 获取 属性,它从当前实例(您的用户控制)。

从不 在 CLR 包装器 (public bool PingState) 中放置额外的代码。当正确访问 属性 时,绑定系统或其他方式不会调用它。要获得 属性 更改的回调,请使用 metadata upon property registration.

如果您想要 属性 的值,您需要保存该值的实例,如前面的评论和答案中所述。使用 setter/singleton 或任何适合您的方式获取实例。 Dependency/attached 属性无法解决您的问题。 (如果您随后想要绑定到 属性,请使用依赖项 属性。)

感谢@aQsu,我能够以不同的方式解决这个问题。我现在使用 Singleton 来获取如下实例:

        private static MainWindow _instance;

    public static MainWindow Instance
    {
        get
        {
            if (_instance == null)
                _instance = new MainWindow();

            return _instance;
        }
    }

然后只需调用 UserControl

            bool ping = MainWindow.Instance.PingState;