Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign global enum as Tag value in XAML?

Tags:

c#

.net

enums

wpf

xaml

I read several questions on the subject, but the answers do not work for me. I have the following enum that is declared in StlContainer.cs:

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

The enum is declared outside the StlContainer class definition which makes it a global enum. I want to assign its values to the Tag property of different XAML controls, so I tried to do it like this:

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

But got the error:

Error 1 Unknown build error, 'Key cannot be null. Parameter name: key Line 234 Position 43.' D:\Visual Studio\Projects\Dental Viewer\Dental Viewer 1.2\Dental Viewer\MainWindow.xaml 234 43 Dental Viewer 1.2

I tried moving the enum to MainWindow.xaml.cs, I tried

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

and

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

I tried to assign this to a Tag on a Label control and still get the same error. What am I missing here? Can I use some kind of Binding to workaround this?

PS: When I type in the value and get to Tag="{x:Static }" the autocomplete only suggests the Member parameter to complete it like this Tag="{x:Static Member=}" if that even matters.

like image 543
mandarin Avatar asked Jan 14 '15 10:01

mandarin


2 Answers

Try to use this expression:

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

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

Or you can create a static class like so:

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

In XAML also used like this:

Tag="{x:Static local:ToothVisualModelClass.Tooth}"
like image 119
Anatoliy Nikolaev Avatar answered Oct 22 '22 01:10

Anatoliy Nikolaev


I found the solution after reading this. I thought this was done automatically or internally, but the solution is that I have to explicitly declare the local namespace in the Window tag like so:

xmlns:local="clr-namespace:Dental_Viewer"

Then <xctk:ColorPicker Tag="{x:Static local:ToothVisualModelType.Tooth}"/> works like a charm.

like image 37
mandarin Avatar answered Oct 22 '22 00:10

mandarin