【问题标题】:Referencing enum defined in a class from within XAML从 XAML 中引用类中定义的枚举
【发布时间】:2010-10-10 20:15:31
【问题描述】:

在 Expression Blend 4(Silverlight 项目)中,我有一个 UserControl,我已向其中添加了一个 CLR 属性。该属性是枚举类型,在 UC 中定义。我已将 ChangePropertyAction 行为附加到 UC 的一个实例。但是,XAML 解析器会给出以下错误(以及其他错误):

“+”在名称中无效

这是因为已生成以下 XAML (sn-p):

<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>

背后的代码:

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

    public MyEnum MyProp
    {
        get; set;
    }

    public enum MyEnum
    {
        First,
        Second,
        Third
    }
}

一个简单的解决方法是从类中“提升”枚举(例如 SomeControl_MyEnum),但有更清洁的解决方案吗?

【问题讨论】:

    标签: silverlight xaml expression-blend


    【解决方案1】:

    不支持在 Xaml 中使用嵌套类型名称。您仍然可以在不引用类型名称的情况下指定属性的值。以下任何一项都应该有效:

    <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>
    

    <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>
    

    如果能够从 Xaml 中引用 MyEnum 类型对您很重要,则需要将定义移出 SomeControl 类。

    【讨论】:

      【解决方案2】:

      您需要使用x:Static 标记扩展,不要忘记根据需要在 XAML 中添加命名空间。

      示例是:

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

      如果您想将绑定引入方程式,请阅读this

      【讨论】:

      • 感谢您的回复。然而事实证明,x:Static 只是 WPF,我没有提到我的项目是 Silverlight。对不起,我太笨了。
      • 经过多次反复试验,我发现我可以简单地替换 ChildPropertyAction.Value 元素并将所需的枚举值插入为父元素的 Value 属性。当然,每次我在 Blend 中更改 ChangePropertyAction 行为时,我都必须返回并再次编辑。
      • 啊,我知道我在标签中确实提到了 Silverlight,但没有在正文中提及。已更新帖子以澄清。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-03
      • 2012-12-26
      • 1970-01-01
      相关资源
      最近更新 更多