Acrotygma
Acrotygma

Reputation: 2569

Change style on status change

I have a rectangle on my view that should change its background color according to the value of a property on the view model.

<Rectangle DataContext="{Binding State}" />

View model

public class MyViewModel {

    // dummy property
    public Status State { get; private set; }

}

Status

public enum Status {
    State1,
    State2,
    State3
}

How can I hookup the rectangle on the view to the various possible states now? Is this a EventTrigger, DataTrigger or do I have to create a ControlTemplate? I'm only asking for the things that needs to be done on the view, the view model etc. is already working correctly and notifying the status changes.

Upvotes: 0

Views: 55

Answers (2)

dkozl
dkozl

Reputation: 33364

You can bind Rectangle.Fill to Status through custom IValueConverter

<Rectangle Fill="{Binding State, Converter={StaticResource StatusConverter}}" />

and converter would looks something like this:

public class StatusConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        switch ((Status)value)
        {
            case Status.State1:
                return new SolidColorBrush(Colors.Red);
            case Status.State2:
                return new SolidColorBrush(Colors.Green);
            case Status.State3:
                return new SolidColorBrush(Colors.Blue);
            default:
                throw new ArgumentException();
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Upvotes: 1

SWilko
SWilko

Reputation: 3612

Datatriggers should do the job of changing the rectangle background on your viewmodel status change. Something like this

<Window.Resources>
    <Style TargetType="Rectangle">
        <Style.Triggers>
            <DataTrigger Binding="{Binding Path=State}" Value="State1">
                <Setter Property="Fill" Value="Red" />
            </DataTrigger>
            <DataTrigger Binding="{Binding Path=State}" Value="State2">
                <Setter Property="Fill" Value="Blue" />
            </DataTrigger>
        </Style.Triggers>
    </Style>
</Window.Resources>

Hope that helps

Upvotes: 0

Related Questions