仿照DevExpress的ReadOnlyDependencyPropertyBindingBehavior编写了一个自己的ReadonlyBindingBehavior。使用需要安装Microsoft.Xaml.Behaviors。绑定时注意使用OneWayToSource。如何使用请参考DevExpress的例子。
public class ReadonlyBindingBehavior : Behavior<FrameworkElement>
{
protected override void OnAttached()
{
base.OnAttached();
Bind();
}
private void Bind()
{
if (string.IsNullOrEmpty(Path))
return;
var binding = new Binding
{
Source = AssociatedObject,
Path = new PropertyPath(Path),
Mode = BindingMode.OneWay
};
BindingOperations.SetBinding(this, DataProperty, binding);
}
public object Data
{
get => GetValue(DataProperty);
set => SetValue(DataProperty, value);
}
public static readonly DependencyProperty DataProperty =
DependencyProperty.Register(nameof(Data), typeof(object), typeof(ReadonlyBindingBehavior), new PropertyMetadata(OnDataPropertyChanged));
private static void OnDataPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var behavior = (ReadonlyBindingBehavior)d;
behavior.Binding = behavior.Data;
}
public object Binding
{
get => GetValue(BindingProperty);
set => SetValue(BindingProperty, value);
}
public static readonly DependencyProperty BindingProperty =
DependencyProperty.Register(nameof(Binding), typeof(object), typeof(ReadonlyBindingBehavior));
public string Path
{
get => (string)GetValue(PathProperty);
set => SetValue(PathProperty, value);
}
public static readonly DependencyProperty PathProperty =
DependencyProperty.Register(nameof(Path), typeof(string), typeof(ReadonlyBindingBehavior), new PropertyMetadata(OnPathPropertyChanged));
private static void OnPathPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
(d as ReadonlyBindingBehavior)?.Bind();
}
}