Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Enum Value as a Command Parameter

Part of this question has been answered on how to bind to an enum as a command parameter, but I need to go one step further.

I have a data template that links to a menu and each menu option initiates a command with a different value of the enum. How do I do this? Do I need to resort to just passing a string?

public enum TestEnum
{
  First,
  Second,
  Third
}
<DataTemplate>
    <MenuItem Header="{Binding Path=.}" Command="{Binding ACommand}" 
        CommandParameter="{Binding Path=???}" />
</DataTemplate>

I want the first MenuItem to bind to Enum.First, the second one to Enum.Second, and so on. I want this written, so that I only have to write the data template above once within a Menu instead of a menu item for each enum.value. HTH.

I need the command parameter to be different for each menu item. So I will have 3 menu items of first, second, and third.

like image 997
kevindaub Avatar asked Apr 21 '11 14:04

kevindaub


1 Answers

Not sure I understand your requirement correctly... is this what you want?

CommandParameter="{Binding Path={x:Static local:TestEnum.First}}"

EDIT: ok, I think I understand now... If you want the enum values as the ItemsSource, you could do it with an ObjectDataProvider, but there's a better way: write a markup extension that takes in the type of the enum and returns the values.

Markup extension

[MarkupExtensionReturnType(typeof(Array))]
public class EnumValuesExtension : MarkupExtension
{
    public EnumValuesExtension()
    {
    }

    public EnumValuesExtension(Type enumType)
    {
        this.EnumType = enumType;
    }

    [ConstructorArgument("enumType")]
    public Type EnumType { get; set; }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return Enum.GetValues(EnumType);
    }
}

XAML

<MenuItem ItemsSource="{my:EnumValues EnumType=my:TestEnum}" Name="menu">
    <MenuItem.ItemContainerStyle>
        <Style TargetType="MenuItem">
            <Setter Property="Header" Value="{Binding}" />
            <Setter Property="Command" Value="{Binding SomeCommand, ElementName=menu}" />
            <Setter Property="CommandParameter" Value="{Binding}" />
        </Style>
    </MenuItem.ItemContainerStyle>
</MenuItem>
like image 54
Thomas Levesque Avatar answered Sep 18 '22 15:09

Thomas Levesque