问题
I have EntitiesUserControl
responsible for EntitiesCount
dependency property:
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); }
}
Another (primary) control include EntitiesUserControl
and read it property through binding:
<controls:EntitiesUserControl EntitiesCount="{Binding CountOfEntities, Mode=OneWayToSource}" />
CountOfEntities
property in view model just store and process changing of count value:
private int countOfEntities;
public int CountOfEntities
{
protected get { return this.countOfEntities; }
set
{
this.countOfEntities = value;
// Custom logic with new value...
}
}
I need EntitiesCount
property of EntitiesUserControl
to be read-only (primary control must not change it, just read) and it works this way only because Mode=OneWayToSource
declared explicitly. But if declare TwoWay
mode or don't explicitly declare mode, then EntitiesCount
could be rewritten from outside (at least right after binding initialization, because it happens after default dependency property value assigned).
I can't do 'legal' read-only dependency property due to binding limitations (best described in this answer), so I need to prevent bindings with mode other than OneWayToSource
. It would be best to have some OnlyOneWayToSource flag like BindsTwoWayByDefault
value in FrameworkPropertyMetadataOptions enumeration...
Any suggestions how to achieve this?
回答1:
It's a „bit” hacky, but you can create a Binding
-derived class and use that instead of 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;
}
}
}
}
In XAML:
<controls:EntitiesUserControl EntitiesCount="{local:OneWayToSourceBinding CountOfEntities}" />
The namespace mapping local
might be something else for you.
This OneWayToSourceBinding
sets the Mode
to OneWayToSource
and prevents setting it to anything else.
来源:https://stackoverflow.com/questions/35634609/allow-only-onewaytosource-binding-mode