Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataStateBehavior for Enum instead of bool? String?

Is there an easy way in WPF to bind VisualStates to enum values? Kinda like DataStateBehavior, but for an Enum?

like image 379
Firoso Avatar asked Jun 14 '10 23:06

Firoso


2 Answers

The best way is to just go ahead and implement a Behavior that does just that -

public class EnumStateBehavior : Behavior<FrameworkElement>
{
    public object EnumProperty
    {
        get { return (object)GetValue(EnumPropertyProperty); }
        set { SetValue(EnumPropertyProperty, value); }
    }

    // Using a DependencyProperty as the backing store for EnumProperty.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty EnumPropertyProperty =
        DependencyProperty.Register("EnumProperty", typeof(object), typeof(EnumStateBehavior), new UIPropertyMetadata(null, EnumPropertyChanged));

    static void EnumPropertyChanged(object sender, DependencyPropertyChangedEventArgs e)
    {
        if (e.NewValue == null) return;

        EnumStateBehavior eb = sender as EnumStateBehavior;

        VisualStateManager.GoToElementState(eb.AssociatedObject, e.NewValue.ToString(), true);
    }

}

The usage is extremely simple - use as follows:

<i:Interaction.Behaviors>
        <local:EnumStateBehavior EnumProperty="{Binding MyEnumProperty}" />
</i:Interaction.Behaviors>
like image 122
Elad Katz Avatar answered Sep 28 '22 09:09

Elad Katz


You can do it in pure xaml by using a DataTrigger per possible enum value with each trigger calling GoToStateAction with a different state. See the example below. For more details take a look at Enum driving a Visual State change via the ViewModel.

    <i:Interaction.Triggers>
        <ei:DataTrigger Binding="{Binding ConfirmedAnswerStatus}" Value="Unanswered">
            <ei:GoToStateAction StateName="UnansweredState" UseTransitions="False" />
        </ei:DataTrigger>
        <ei:DataTrigger Binding="{Binding ConfirmedAnswerStatus}" Value="Correct">
            <ei:GoToStateAction StateName="CorrectlyAnsweredState" UseTransitions="True" />
        </ei:DataTrigger>
        <ei:DataTrigger Binding="{Binding ConfirmedAnswerStatus}" Value="Incorrect">
            <ei:GoToStateAction StateName="IncorrectlyAnsweredState" UseTransitions="True" />
        </ei:DataTrigger>
    </i:Interaction.Triggers>
like image 35
Manuel Laflamme Avatar answered Sep 28 '22 08:09

Manuel Laflamme