Enum的DataStateBehavior而不是bool?串?

Fir*_*oso 6 data-binding wpf behavior

在WPF中有一种简单的方法将VisualStates绑定到枚举值吗?有点像DataStateBehavior,但对于Enum?

Ela*_*atz 4

最好的方法就是继续实施一个能够做到这一点的行为 -

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

}
Run Code Online (Sandbox Code Playgroud)

使用方法极其简单——使用方法如下:

<i:Interaction.Behaviors>
        <local:EnumStateBehavior EnumProperty="{Binding MyEnumProperty}" />
</i:Interaction.Behaviors>
Run Code Online (Sandbox Code Playgroud)