I have a custom TextBox
control which is inheriting System.Windows.Controls.TextBox
and implementing INotifyPropertyChanged
interface .
public partial class V3TextBox : TextBox, INotifyPropertyChanged
It has a custom OriginalValue
property and is overriding base Text
property.
The way I imagined for it to work is to bind Text
and OriginalValue
to two different string properties and to set its Background
to , let's say, yellow if those two strings are not the same and back to white if they become the same again.
These are my Text
and PropertyChanged
properties:
private Binding PropertyChangedBinding = new Binding()
{
Path = new PropertyPath("ChangedPropertyBackground")
};
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string name)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
private string text { get; set; } = "";
public new string Text
{
get
{
return text;
}
set
{
text = value;
if (value == originalValue)
BindingOperations.ClearBinding(this, BackgroundProperty);
else
SetBinding(BackgroundProperty, PropertyChangedBinding);
OnPropertyChanged("Background");
}
}
Now, the problem is probably with setting DependencyProperty
for my OriginalValue
property.
They look like this:
private string originalValue;
public string OriginalValue
{
get
{
return (string)GetValue(TestProperty);
}
set
{
originalValue = value;
SetValue(TestProperty, value);
}
}
public static readonly DependencyProperty TestProperty =
DependencyProperty.Register("OriginalValue", typeof(string),
typeof(V3TextBox), new FrameworkPropertyMetadata(default(string)));
private void OnTextPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
SetValue(TestProperty, e.NewValue);
}
Control usage in XAML
looks like this:
<Ctrls:V3TextBox x:Name="txtBxDiscountNote"
Text="{Binding EditedNote, Mode=TwoWay, NotifyOnTargetUpdated=True}"
OriginalValue="{Binding OriginalNote, Mode=TwoWay}"/>
DataContext
is set in XAML
.
The problem is that the OriginalValue
property is never changed, it is always null
and the code for changing Background
is triggered only when Text
property is changed programmatically, not via GUI input. Would this be easier to implement with IValueConverter
? There will be around 30 of these controls on a single form.
Something like this should work:
Use it like this: