我让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
属性的EntitiesUserControl
为只读(主控件不能更改它,只需读取),而且它的工作方式仅是因为Mode=OneWayToSource
显式声明。但是,如果声明TwoWay
模式或不显式声明模式,那么EntitiesCount
可以从外部重写(至少在绑定初始化之后,因为在指定默认依赖项属性值之后发生)。
由于绑定限制(最好在此answer中描述),我无法执行“合法”只读依赖属性,因此我需要防止使用OneWayToSource
以外的模式进行绑定。最好在OnlyOneWayToSource枚举中有一些像BindsTwoWayByDefault
值这样的FrameworkPropertyMetadataOptions
标志.
有何建议可以做到这一点?
发布于 2016-02-25 11:13:53
这是一个“位”黑客,但您可以创建一个Binding
-derived类,并使用它而不是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
,并防止将其设置为任何其他内容。
https://stackoverflow.com/questions/35634609
复制