C# WPF:创建附加的可绑定属性
我正在尝试添加一个属性,该属性可以附加到任何控件并向其绑定一个值C# WPF:创建附加的可绑定属性,c#,wpf,C#,Wpf,我正在尝试添加一个属性,该属性可以附加到任何控件并向其绑定一个值 public class ValidationBorder : DependencyObject { public static readonly DependencyProperty HasErrorProperty = DependencyProperty.Register( "HasError", typeof(b
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中指定绑定
从属对象
有什么问题吗
我已经尝试了我在网上能找到的一切:
- 在绑定中添加括号
- 添加相对资源
- 将
更改为DependencyProperty.Register
DependencyProperty.RegisterAttached
的不同类型包括typeof(UIElement)
typeof(TextBox)
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
。同时删除hasrerror
属性。有关详细信息,请参阅。尝试以下实现:
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
。同时删除hasrerror
属性。有关详细信息,请参阅。typeof(UIElement)
错误,对于使用的附加属性RegisterAttached()
方法,它应该是typeof(ValidationBorder)
。typeof(UIElement)
错误,它应该是typeof(ValidationBorder)
对于附加的属性,您使用RegisterAttached()
方法。