I have two textboxes for the firstname and second name of a user and I have created a converter to change the background colour of the textbox when the text equals a specific string. The problem I am having is that the textbox will only update at run time and doesn't update when I change the text is the textbox.
XAML:
<TextBox x:Name="forenameTextBox" Grid.Column="1" HorizontalAlignment="Left" Height="23" Margin="3" Grid.Row="1"
Background="{Binding Staff,Converter ={StaticResource StaffNameToBackgroundColourConverter1}}"
Text="{Binding Staff.Forename, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" VerticalAlignment="Center" Width="120"/>
<Label Content="Surname:" Grid.Column="0" HorizontalAlignment="Left" Margin="3" Grid.Row="2" VerticalAlignment="Center"/>
<TextBox x:Name="surnameTextBox" Grid.Column="1" HorizontalAlignment="Left" Height="23" Margin="3" Grid.Row="2"
Background="{Binding Staff,Converter={StaticResource StaffNameToBackgroundColourConverter1}}"
Text="{Binding Staff.Surname, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" VerticalAlignment="Center" Width="120"/>
Converter code:
public class StaffNameToBackgroundColourConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var staff = (Staff) value;
if (staff.Forename == "Donald" && staff.Surname == "Duck")
{
return "Yellow";
}
else
{
return "White";
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return value;
}
}
Correct text input:
Wrong text input - no change:
You need to add UpdateSourceTrigger=PropertyChanged
to your Binding
:
<TextBox x:Name="forenameTextBox" Grid.Column="1" HorizontalAlignment="Left"
Height="23" Margin="3" Grid.Row="1" Background="{Binding Staff,
UpdateSourceTrigger=PropertyChanged, Converter ={StaticResource
StaffNameToBackgroundColourConverter1}}" Text="{Binding Staff.Forename,
Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}"
VerticalAlignment="Center" Width="120"/>
<TextBox x:Name="surnameTextBox" Grid.Column="1" HorizontalAlignment="Left" Height="23"
Margin="3" Grid.Row="2" Background="{Binding Staff,
UpdateSourceTrigger=PropertyChanged, Converter={StaticResource
StaffNameToBackgroundColourConverter1}}" Text="{Binding Staff.Surname, Mode=TwoWay,
NotifyOnValidationError=true, ValidatesOnExceptions=true}"
VerticalAlignment="Center" Width="120"/>
This will update the binding source as the user types each letter. You can find out more from the Binding.UpdateSourceTrigger Property page at MSDN.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With