WPF:创建附加的可绑定属性

时间:2019-03-08 14:07:38

标签: c# wpf

我正在尝试添加一个属性,该属性可以附加到任何控件上并为其绑定一个值。

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);
        }
    }

我的用法:

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

当我启动项目时,它显示错误(已翻译):

  

不能在TextBox setHasError属性中指定绑定。   只能在的DependencyProperty中指定绑定   DependencyObject

这可能是什么问题?

我已经尝试了所有可以在网上找到的内容:

  • 在绑定中添加括号
  • 添加RelativeSource
  • DependencyProperty.Register更改为DependencyProperty.RegisterAttached
  • typeof(UIElement)的不同类型,包括typeof(TextBox)

1 个答案:

答案 0 :(得分:1)

尝试此实现:

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);
    }
}

您应该致电RegisterAttached并将所有者类型设置为ValidationBorder。同时删除HasError属性。有关更多信息,请参阅docs

相关问题