Access enumeration type defined in view model from

2019-07-27 04:36发布

问题:

In my MVVM WPF app, I have declared an enumeration:

View model:

namespace MyViewModel
{
    public class MyViewModelClass  
    {
      public enum MessageTypes
      {
          Info = 0,
          Error = 1
      };
    }
}

Now from the view I am trying to access it in order to use it as static resource in a control so:

View:

xmlns:vm="clr-namespace:MyViewModel;assembly=MyViewModelAssembly"

<Image>
   <Image.Style>
        <Style TargetType="{x:Type Image}">
            <Setter Property="Source" Value="/Common.Images;component/Images/Info.png"/>
            <Style.Triggers>
                <DataTrigger Binding="{Binding MessageTypes}" Value="{x:Static vm:MessageTypes.Error}">
                    <Setter Property="Source" Value="/Common.Images;component/Images/Cancel.png"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
   </Image.Style>
</Image>

The problem here is that line Value="{x:Static vm:MessageTypes.Error}" is not being recognized. Compilation error:

'MessageTypes' type not found.

回答1:

The enum is declared as a nested type (in class MyViewModelClass), which is not supported by the x:Static markup extension.

You should declare it like this:

namespace MyViewModel
{
    public enum MessageTypes
    {
        Info = 0,
        Error = 1
    }

    public class MyViewModelClass  
    {
        ...
    }
}