我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
值......
有任何建议如何实现这一目标?
答案 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
可能适合您。
此OneWayToSourceBinding
将Mode
设置为OneWayToSource
并阻止将其设置为其他任何内容。