tags:

views:

47

answers:

1

I am using my custom validation engine to validate my ViewModel properties. I am stuck at the last step. I want to change the background color of the TextBox when the validation fails. So, I implemented DataTriggers and binded it to the HasError property. HasError is a normal CLR property.

  public bool HasError
        {
            get
            {
                var hasError = Errors.Count() > 0;
                return hasError;
            }
        }

And here is the code:

 <Style x:Key="textBoxStyle" TargetType="{x:Type TextBox}">                   

            <Style.Triggers>

                <DataTrigger Binding="{Binding Path=HasError}" Value="True">

                    <Setter Property="Background" Value="Red" />
                </DataTrigger>          


            </Style.Triggers>

        </Style>

The problem is that it will be fired only once when the this.DataContext is assigned to a view model. So, I thought maybe I can use Dependency Property instead of the normal property but that did not worked out either.

Any ideas?

UPDATE:

It seems like the DataTriggers are only fired when hooked to the CLR properties and not the dependency properties.

UPDATE 2:

If only the following code worked:

 ****<Trigger Property="{Binding Path=HasError}" Value="True">
                    <Setter Property="Background" Value="Red" />
                </Trigger>****  

UPDATE 3 WORKING:

As the answer mentioned I had to fire the INotifyPropertyChanged event.

public ObservableCollection Errors { get { return (ObservableCollection)GetValue(ErrorsProperty); } set { SetValue(ErrorsProperty, value);

            OnPropertyChanged("HasError");

        }
    }
+1  A: 

WPF system will never know that your HasError property changed, that's why it's fired only once. On of methods is implementing INotifyPropertyChanged and firing PropertyChanged events whec colletion of errors changes.

Yurec
Oh you are a savior! Thanks a million. I have updated the code to reflect the changes.
azamsharp
Ah found a bug in my code. All the properties are dependent on the Errors collection. Which means all the colored red if there is a single entry in errors collection.
azamsharp