Reputation: 8462
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:
DependencyProperty.Register
to DependencyProperty.RegisterAttached
typeof(UIElement)
including typeof(TextBox)
Upvotes: 0
Views: 188
Reputation: 169390
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.
Upvotes: 2