【发布时间】: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。