R – WPF Data Triggers and Changing the Style of the Control

datatriggerwpf

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");

        }
    }

Best Answer

WPF system will never know that your HasError property changed, that's why it only fires once. One of the methods to accomplish this is implementing INotifyPropertyChanged and firing PropertyChanged events when the collection of errors changes.

Related Topic