C# 仅允许单向源绑定模式

C# 仅允许单向源绑定模式,c#,wpf,xaml,data-binding,dependency-properties,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

我有
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}" />
我需要
EntitiesUserControl
EntitiesCount
属性成为只读的(主控件不能更改它,只能读取),并且它以这种方式工作只是因为显式声明了
Mode=OneWayToSource
。但是,如果声明
TwoWay
模式或不显式声明模式,则可以从外部重写
EntitiesCount
(至少在绑定初始化之后,因为它发生在指定的默认依赖属性值之后)

由于绑定限制,我无法执行“合法”只读依赖项属性(最好在本文中介绍),因此我需要防止使用非
OneWayToSource
模式的绑定。最好在枚举中使用一些onlyonwaytosource标志,如默认情况下的
bindstwoway


如何实现这一点,有什么建议吗?

这是一个“有点”麻烦的问题,但是您可以创建一个
绑定
派生类,并使用它来代替
绑定

[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
可能对您来说是另一回事


OneWayToSourceBinding
模式设置为
OneWayToSource
,并防止将其设置为任何其他模式。

我不确定使用
模式=OneWayToSource
有什么问题。唯一的问题是你得把它打出来还是怎么着?对不起,我不太明白这个问题。我将分享一种只实现
OneWayToSource
绑定的黑客方法,但不确定这是否是您所需要的。@SzabolcsDézsi问题不在于我必须键入,问题只是另一种方式——我可能不会键入,并且没有任何东西会告诉我我将以不应该使用的方式使用属性。类似地,如果您编写的代码将值赋给只读属性,则无法编译程序。@Sam FWIW我同意您的看法,并希望看到一个优雅的解决方案。但XAML或WPF似乎并不支持您所指的安全理念:(例如,谢谢,这很有趣,至少我用这种方式使用了较新的绑定…这并不完全是我需要的,但它有点相对:就像您的自定义绑定阻止使用除“OneWayToSource”以外的任何模式一样,我需要依赖性属性来阻止绑定到自身任何绑定(自定义绑定或任何标准绑定除外)使用“OneWayToSource”以外的模式进行rt绑定。
<controls:EntitiesUserControl EntitiesCount="{local:OneWayToSourceBinding CountOfEntities}" />