views:

26

answers:

1

I have a page which has got several text boxes. These controls are bound to a model. I am using MVVM.

Assume I have three text boxes, FirstName, LastName and Company. So in the model, I have three properties to bind. Now I need to track the changes happened to each field. If FirstName changes from original value, I need the text box to be colored with a different background color.

Currently I am creating another property called FirstNameChanged and binding the background to this property. This will be updated when I change the FirstName. For 3 fields, this seems to be OK. But when I have more fields, the number of properties will be too much.

Is there a better way to handle this?

A: 

It is not quite clear what you mean by tracking the changes. If you only mean that the text boxes should change colour when you edit a field, then this is how I would solve it.

Since this is a view specific functionality, the code should be in the code-behind of the view and should not be in the viewmodel.

So I would do the following:

Create an event handler for text changing in the textboxes:

private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
    TextBox textbox = sender as TextBox;
    textbox.Background = new SolidColorBrush(Colors.Green);
}

and then bind the TextChanged event of all the textboxes to this event handler.

Johannes