If you want to have a TextBox with a new property, the way is to inherit from the TextBox and add the new property as a DependencyProperty.
Example where the HasErrors property is added, which when true
puts the Background in red.
public class HasErrorsTextBox : TextBox
{
private Brush NoErrorsBackgroundColor { get; set; }
public static readonly DependencyProperty HasErrorsProperty = DependencyProperty.Register(
"HasErrors",
typeof(bool),
typeof(HasErrorsTextBox),
new FrameworkPropertyMetadata(false, OnHasErrorsChanged)
);
public bool HasErrors
{
get { return (bool)GetValue(HasErrorsProperty); }
set { SetValue(HasErrorsProperty, value); }
}
private static void OnHasErrorsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var textBox = d as HasErrorsTextBox;
if (textBox.NoErrorsBackgroundColor == null)
{
textBox.NoErrorsBackgroundColor = textBox.Background;
}
textBox.Background = (bool)e.NewValue ? Brushes.Red : textBox.NoErrorsBackgroundColor;
}
}
How to use:
<local:HasErrorsTextBox Text="HasErrorsTextBox" HasErrors="True"/>
Another approach is to create an Attached Property . This approach allows you to create a property that can be associated ( Attached ) with the same group of components.
In this example, it could be applied to any component that has the Background property (any type that inherits from Control).
Example implementing an Attached Property :
public static class MyAttachedProperties
{
private static Brush NoErrorsBackgroundColor { get; set; }
public static readonly DependencyProperty HasErrorsProperty = DependencyProperty.RegisterAttached(
"HasErrors",
typeof(bool),
typeof(MyAttachedProperties),
new FrameworkPropertyMetadata(false, OnHasErrorsChanged)
);
public static bool GetHasErrors(DependencyObject d)
{
return (bool)d.GetValue(HasErrorsProperty);
}
public static void SetHasErrors(DependencyObject d, bool value)
{
d.SetValue(HasErrorsProperty, value);
}
private static void OnHasErrorsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var control = d as Control;
if (control == null)
{
throw new
InvalidOperationException("Esta propriedade apenas pode ser aplicada a objectos do tipo Control");
}
if (NoErrorsBackgroundColor == null)
{
NoErrorsBackgroundColor = control.Background;
}
control.Background = (bool)e.NewValue ? Brushes.Red : NoErrorsBackgroundColor;
}
}
How to use:
<TextBox Text="AttachedProperty" local:MyAttachedProperties.HasErrors="True"/>