简体   繁体   中英

WPF: Creating attached bindable property

I'm trying to add a property, that can be attached to any control and bind a value to it.

public class ValidationBorder : DependencyObject
    {
        public static readonly DependencyProperty HasErrorProperty =
            DependencyProperty.Register(
                "HasError",
                typeof(bool?),
                typeof(UIElement),
                new PropertyMetadata(default(Boolean))
            );

        public bool? HasError
        {
            get { return (bool?) GetValue(HasErrorProperty); }
            set {  SetValue(HasErrorProperty, value);}
        }

        public static void SetHasError(UIElement element, Boolean value)
        {
            element.SetValue(HasErrorProperty, value);
        }
        public static Boolean GetHasError(UIElement element)
        {
            return (Boolean)element.GetValue(HasErrorProperty);
        }
    }

My usage:

<TextBox Text="{Binding SelectedFrequencyManual, UpdateSourceTrigger=PropertyChanged}" TextAlignment="Center"
                         attached:ValidationBorder.HasError="{Binding Path=DataOutOfRange}">
                </TextBox>

When I start the project it displays error (translated):

A Binding cannot be specified in the TextBox setHasError property. Only a Binding can be specified in a DependencyProperty of a DependencyObject

What can be wrong with it?

I've tried everything I could find on the web:

  • Add parenthesis in the binding
  • Add RelativeSource
  • Change DependencyProperty.Register to DependencyProperty.RegisterAttached
  • Different types for typeof(UIElement) including typeof(TextBox)

Try this implementation:

public class ValidationBorder
{
    public static readonly DependencyProperty HasErrorProperty =
        DependencyProperty.RegisterAttached(
            "HasError",
            typeof(bool?),
            typeof(ValidationBorder),
            new PropertyMetadata(default(bool?))
        );

    public static void SetHasError(UIElement element, bool? value)
    {
        element.SetValue(HasErrorProperty, value);
    }
    public static bool? GetHasError(UIElement element)
    {
        return (bool?)element.GetValue(HasErrorProperty);
    }
}

You should call RegisterAttached and set the owner type to ValidationBorder . Also remove the HasError property. Please refer to the docs for more information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM