仅允许OneWayToSource绑定模式

时间:2016-02-25 17:49:01

标签: c# wpf xaml data-binding dependency-properties

EntitiesUserControl负责EntitiesCount依赖属性:

public static readonly DependencyProperty EntitiesCountProperty = DependencyProperty.Register(
    nameof(EntitiesCount),
    typeof(int),
    typeof(EntitiesUserControl),
    new FrameworkPropertyMetadata(1, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));

public int EntitiesCount
{
    get { return (int)this.GetValue(EntitiesCountProperty); }
    set { this.SetValue(EntitiesCountProperty, value); }
}

另一个(主要)控件包括EntitiesUserControl并通过绑定读取它的属性:

<controls:EntitiesUserControl EntitiesCount="{Binding CountOfEntities, Mode=OneWayToSource}" />
视图模型中的

CountOfEntities属性只是存储和处理计数值的更改:

private int countOfEntities;
public int CountOfEntities
{
    protected get { return this.countOfEntities; }
    set
    {
        this.countOfEntities = value;
        // Custom logic with new value...
    }
}

我需要EntitiesCount的{​​{1}}属性为只读(主要控件不能更改它,只需读取)并且它的工作方式只是因为{{1明确声明。但是如果声明EntitiesUserControl模式或者没有显式声明模式,那么Mode=OneWayToSource可以从外部重写(至少在绑定初始化之后,因为它发生默认依赖属性之后)价值分配)。

由于绑定限制(我在answer中最好描述),我无法做'合法'只读依赖属性,因此我需要阻止使用TwoWay以外的模式进行绑定。最好在FrameworkPropertyMetadataOptions枚举中有一些 OnlyOneWayToSource 标记,如EntitiesCount值......

有任何建议如何实现这一目标?

1 个答案:

答案 0 :(得分:2)

这有点“hacky”,但你可以创建一个Binding派生类并使用它来代替Binding

[MarkupExtensionReturnType(typeof(OneWayToSourceBinding))]
public class OneWayToSourceBinding : Binding
{
    public OneWayToSourceBinding()
    {
        Mode = BindingMode.OneWayToSource;
    }

    public OneWayToSourceBinding(string path) : base(path)
    {
        Mode = BindingMode.OneWayToSource;
    }

    public new BindingMode Mode
    {
        get { return BindingMode.OneWayToSource; }
        set
        {
            if (value == BindingMode.OneWayToSource)
            {
                base.Mode = value;
            }
        }
    }
}

在XAML中:

<controls:EntitiesUserControl EntitiesCount="{local:OneWayToSourceBinding CountOfEntities}" />

命名空间映射local可能适合您。

OneWayToSourceBindingMode设置为OneWayToSource并阻止将其设置为其他任何内容。