【问题标题】:WPF: Creating attached bindable propertyWPF:创建附加的可绑定属性
【发布时间】:2019-03-08 14:07:37
【问题描述】:

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

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 中指定 Binding 依赖对象

这有什么问题?

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

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

【问题讨论】:

  • typeof(UIElement)错了,应该是typeof(ValidationBorder)
  • 对于 attached 属性,您使用RegisterAttached() 方法indeed

标签: c# wpf


【解决方案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

【讨论】:

    猜你喜欢
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-22
    相关资源
    最近更新 更多