c# - XAML 绑定(bind)到复杂值对象

标签 c# wpf xaml oop binding

我有一个复杂的值对象类,它具有 1) 数字或只读属性; 2)私有(private)构造函数;和 3) 许多静态单例实例属性 [因此 ComplexValueObject 的属性永远不会改变,并且单个值在应用程序的生命周期中实例化一次]。

public class ComplexValueClass
{
    /* A number of read only properties */
    private readonly string _propertyOne;
    public string PropertyOne
    {
        get
        {
            return _propertyOne;
        }
    }

    private readonly string _propertyTwo;
    public string PropertyTwo
    {
        get
        {
            return _propertyTwo;
        }
    }

    /* a private constructor */
    private ComplexValueClass(string propertyOne, string propertyTwo)
    {
        _propertyOne = propertyOne;
        _propertyTwo = PropertyTwo;
    }

    /* a number of singleton instances */
    private static ComplexValueClass _complexValueObjectOne;
    public static ComplexValueClass ComplexValueObjectOne
    {
        get
        {
            if (_complexValueObjectOne == null)
            {
                _complexValueObjectOne = new ComplexValueClass("string one", "string two");
            }
            return _complexValueObjectOne;
        }
    }

    private static ComplexValueClass _complexValueObjectTwo;
    public static ComplexValueClass ComplexValueObjectTwo
    {
        get
        {
            if (_complexValueObjectTwo == null)
            {
                _complexValueObjectTwo = new ComplexValueClass("string three", "string four");
            }
            return _complexValueObjectTwo;
        }
    }
}

我有一个看起来像这样的数据上下文类:

public class DataContextClass : INotifyPropertyChanged
{


    private ComplexValueClass _complexValueClass;
    public ComplexValueClass ComplexValueObject
    {
        get
        {
            return _complexValueClass;
        }
        set
        {
            _complexValueClass = value;
            PropertyChanged(this, new PropertyChangedEventArgs("ComplexValueObject"));
        } 
    }
}  

我想将 XAML 绑定(bind)语句写入我的复杂值对象上的属性,以便在整个复杂值对象发生变化时更新 UI。最好和/或最简洁的方法是什么?我有类似的东西:

<Object Value="{Binding ComplexValueObject.PropertyOne}" />

但是当 ComplexValueObject 作为一个整体发生变化时,UI 不会更新。

最佳答案

您的原始方案应该工作得很好,因为在大多数情况下,绑定(bind)可以识别其属性路径的任何部分上的更改通知。事实上,我尝试了您发布的代码以进行确认,它确实可以正常工作。

在精简样本中是否还有其他您可能没有表达的复杂性?我能想到的第一个是 collections->ItemsSource Bindings,但可能有一些与您将绑定(bind)值分配给的属性相关的东西(因为它显然不是一个对象)或完全是其他东西。

关于c# - XAML 绑定(bind)到复杂值对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2990328/

相关文章:

javascript - 如何将信息从 WPF 应用程序传递到 HTML 页面

c# - 如何在 Xamarin.Forms 中强制使用灯光模式?

html - 使用边距和/或填充强制元素到位是否被认为是不好的做法?

c# - C#如何做运行时泛型?

转换网格布局

wpf - 为什么每次创建新 View 模型时都不会调用 View 构造函数?

wpf - Xaml 设计器 Visual Studio 2015 中的“无效标记”

c# - web.config 和 app.config 更改的影响

c# - 将 Outlook htmlbody 从右向左对齐

c# - 如何在 asp.net mvc c# 项目中插入脚本