Databinding to CLR property in code-behind

前端 未结 5 1337
隐瞒了意图╮
隐瞒了意图╮ 2021-02-15 20:18

Binding to a Dependency Property is easy in code-behind. You just create a new System.Windows.Data.Binding object, and then call the target dependency object\'s

5条回答
  •  借酒劲吻你
    2021-02-15 21:24

    If I understand your question correctly you have a FrameworkElement that exposes a plain old ordinary property that isn't backed up as a Dependency property. However you would like to set it as the target of a binding.

    First off getting TwoWay binding to work would be unlikely and in most cases impossible. However if you only want one way binding then you could create an attached property as a surrogate for the actual property.

    Lets imagine I have a StatusDisplay framework element that has a string Message property that for some really dumb reason doesn't support Message as a dependency property.

    public static StatusDisplaySurrogates
    {
        public static string GetMessage(StatusDisplay element)
        {
            if (element == null)
            {
                throw new ArgumentNullException("element");
            }
            return element.GetValue(MessageProperty) as string;
        }
    
        public static void SetMessage(StatusDisplay element, string value)
        {
            if (element == null)
            {
                throw new ArgumentNullException("element");
            }
            element.SetValue(MessageProperty, value);
        }
    
        public static readonly DependencyProperty MessageProperty =
            DependencyProperty.RegisterAttached(
                "Message",
                typeof(string),
                typeof(StatusDisplay),
                new PropertyMetadata(null, OnMessagePropertyChanged));
    
        private static void OnMessagePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            StatusDisplay source = d as StatusDisplay;
            source.Message = e.NewValue as String;
        }
    }
    

    Of course if the StatusDisplay control has its Message property modified directly for any reason the state of this surrogate will no longer match. Still that may not matter for your purposes.

提交回复
热议问题