如何在XAML中将全局枚举指定为Tag值?

时间:2015-01-14 10:36:47

标签: c# .net wpf xaml enums

我读了几个关于这个问题的问题,但答案对我不起作用。 我有以下在StlContainer.cs中声明的枚举:

public enum ToothVisualModelType
{
    CoordinateSystemPivot = 0,
    Tooth = 1,
    Crown = 2,
    Gums = 3
}

枚举在StlContainer类定义之外声明,使其成为全局枚举。我想将其值分配给不同XAML控件的Tag属性,所以我尝试这样做:

<xctk:ColorPicker Tag="{x:Static local:ToothVisualModelType.Tooth}" 
                  Name="colorPickerTooth" 
                  Width="110" 
                  Grid.Column="1" 
                  Grid.Row="3" 
                  SelectedColorChanged="colorPickerTooth_SelectedColorChanged" 
                  DisplayColorAndName="True" 
                  Margin="0,0,10,5">
 </xctk:ColorPicker>

但得到了错误:

  

错误1未知的构建错误,'键不能为空。   参数名称:键行234位置43.' D:\ Visual Studio \ Projects \ Dental Viewer \ Dental Viewer 1.2 \ Dental Viewer \ MainWindow.xaml 234 43 Dental Viewer 1.2

我尝试将枚举移动到MainWindow.xaml.cs,我试过

Tag="{x:Static local:StlContainer+ToothVisualModelType.Tooth}"

Tag="{x:Static MyNamespace:ToothVisualModelType.Tooth}"

我尝试将其分配给Label控件上的Tag,但仍然会出现相同的错误。我在这里错过了什么?我可以使用某种Binding来解决这个问题吗?

PS:当我输入值并转到Tag="{x:Static }"时,自动填充功能只会建议使用Member参数来完成它,就像这个Tag="{x:Static Member=}"一样,如果这很重要的话。

2 个答案:

答案 0 :(得分:4)

尝试使用此表达式:

<Control Name="MyControl"
         Width="100"
         Height="30">

    <Control.Tag>
        <x:Static Member="local:ToothVisualModelType.Tooth" />
    </Control.Tag>
</Control>

或者你可以像这样创建一个静态类:

internal static class ToothVisualModelClass
{
    public static string CoordinateSystemPivot = "0";
    public static string Tooth = "1";
    // ...etc...
}

在XAML中也使用如下:

Tag="{x:Static local:ToothVisualModelClass.Tooth}"

答案 1 :(得分:3)

我在阅读this后找到了解决方案。 我认为这是自动或内部完成的,但解决方案是我必须在Window标记中显式声明local命名空间,如下所示:

xmlns:local="clr-namespace:Dental_Viewer"

然后<xctk:ColorPicker Tag="{x:Static local:ToothVisualModelType.Tooth}"/>就像魅力一样。