Referencing enum defined in a class from within XAML

天涯浪子 提交于 2021-02-10 06:15:17

问题


In Expression Blend 4 (Silverlight project) I have a UserControl to which I have added a CLR property. This property is an enum type, which is defined within the UC. I have attached a ChangePropertyAction behaviour to an instance of the UC. However, the XAML parser gives the following error (among others):

'+' is not valid in a name

This is because the following XAML (snippet) has been generated:

<local:SomeControl Margin="155,113,317,0" d:LayoutOverrides="Width, Height">
  <i:Interaction.Triggers>
    <i:EventTrigger EventName="MouseLeftButtonDown">
      <ei:ChangePropertyAction PropertyName="MyProp">
        <ei:ChangePropertyAction.Value>
          <local:SomeControl+MyEnum>Second</local:SomeControl+MyEnum> <----- Error on this line caused by the '+' 
        </ei:ChangePropertyAction.Value>
      </ei:ChangePropertyAction>
    </i:EventTrigger>
  </i:Interaction.Triggers>
</local:SomeControl>

The code behind:

public partial class SomeControl : UserControl
{
    public SomeControl()
    {
        // Required to initialize variables
        InitializeComponent();
    }

    public MyEnum MyProp
    {
        get; set;
    }

    public enum MyEnum
    {
        First,
        Second,
        Third
    }
}

A simple workround is to "promote" the enum out from within the class (eg SomeControl_MyEnum), but is there a cleaner solution?


回答1:


Using a nested type name in Xaml is not supported. You can still specify the value of the property without referring to the type name. Either of the following should work:

<local:SomeControl Margin="155,113,317,0" d:LayoutOverrides="Width, Height">
  <i:Interaction.Triggers>
    <i:EventTrigger EventName="MouseLeftButtonDown">
      <ei:ChangePropertyAction PropertyName="MyProp">
        <ei:ChangePropertyAction.Value>Second</ei:ChangePropertyAction.Value>
      </ei:ChangePropertyAction>
    </i:EventTrigger>
  </i:Interaction.Triggers>
</local:SomeControl>

or

<local:SomeControl Margin="155,113,317,0" d:LayoutOverrides="Width, Height">
  <i:Interaction.Triggers>
    <i:EventTrigger EventName="MouseLeftButtonDown">
      <ei:ChangePropertyAction PropertyName="MyProp" Value="Second" />
    </i:EventTrigger>
  </i:Interaction.Triggers>
</local:SomeControl>

If it is important to you to be able to refer to the MyEnum type from Xaml, you will need to move the definition out of the SomeControl class.




回答2:


You need to make use of the x:Static markup extension, don;t forget to add namespace in XAML as needed.

Sample would be:

"{x:Static Member=MyProject:MyEnum.First}"

If you want to bring in binding into the equation, read this



来源:https://stackoverflow.com/questions/3902002/referencing-enum-defined-in-a-class-from-within-xaml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!