美文网首页
ReadonlyBindingBehavior

ReadonlyBindingBehavior

作者: 勿念情 | 来源:发表于2022-09-07 09:09 被阅读0次

    仿照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();
            }
        }
    

    相关文章

      网友评论

          本文标题:ReadonlyBindingBehavior

          本文链接:https://www.haomeiwen.com/subject/dvonnrtx.html