ReadonlyBindingBehavior

仿照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();
        }
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容