【问题标题】:Implementation of one way dependancy property [duplicate]单向依赖属性的实现[重复]
【发布时间】:2019-08-21 11:25:09
【问题描述】:

我正在使用 WPF 开发自定义用户控件。 我已经注册了 DependancyProperty,但我只想让它成为 OneWay 绑定。有可能做到吗? 这是我所拥有的:

public static readonly DependencyProperty CustomPrProperty =
        DependencyProperty.Register(
            "CustomPr",
            typeof(string),
            typeof(CustomView),
            new FrameworkPropertyMetadata(string.Empty, OnDependencyPropertyChanged));

这样,当有人使用用户控件时,他可以使其成为 OneWay、OneWayToSource 和 TwoWay。我怎样才能使它成为只读属性?

【问题讨论】:

    标签: c# wpf data-binding


    【解决方案1】:

    您可以设置FrameworkPropertyMetadataBindsTwoWayByDefault 属性以指定该属性默认为双向绑定。仍然可以通过将单个绑定的 Mode 属性设置为 TwoWay 以外的其他值来更改模式。

    要创建无法设置的只读依赖属性,应使用RegisterReadOnly 方法:

    internal static readonly DependencyPropertyKey CustomPrKey = DependencyProperty.RegisterReadOnly(
     "CustomPr",
     typeof(string),
     typeof(CustomView),
     new PropertyMetadata(string.Empty)
    );
    
    public static readonly DependencyProperty CustomPrProperty = CustomPrKey.DependencyProperty;
    
    public string CustomPr
    {
        get { return (string)GetValue(CustomPrProperty); }
    }
    

    【讨论】:

    • @ mm8,嗨,我的自定义 DP 设置为使用默认的 TwoWay 绑定,但是当我在 Xaml 中设置 mode=OneWay 时,当我更改绑定属性值时没有任何反应。 DP可以这样用吗?
    猜你喜欢
    • 2010-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-07
    相关资源
    最近更新 更多