4

I have defined an enum in C#

public enum PointerStyle { Pointer, Block, Slider } ; 

I am using it as a dependency property on a WPF custom control

public static DependencyProperty DisplayStyleProperty = DependencyProperty.Register("DisplayStyle", typeof(PointerStyle), typeof(Pointer), new PropertyMetadata(PointerStyle.Pointer)); public PointerStyle DisplayStyle { get { return (PointerStyle)GetValue(DisplayStyleProperty); } set { SetValue(DisplayStyleProperty, value); } } 

and using it in a ControlTemplate

<Trigger Property="DisplayStyle" Value="{x:Static local:PointerStyle.Block}"> 

Very often, but not always, the editor underlines most of the code and shows the error "'Block' is not a valid value for property 'DisplayStype'." as shown in the following screen shot

enter image description here

This is in Visual Studio 2015.

At runtime, the code works perfectly.
In the design window of my test program, the control is rendered totally incorrectly.

What am I doing wrong?
What is the best way to refer to an enum value in XAML?

(I would be happy to use a TypeConverter and to define the value as a string, but I can't find a good example of how do it.)

4
  • Did you try to simply write Value="Block" in the Trigger? Type conversion from string to enum usually works out of the box in XAML. Commented Mar 18, 2017 at 10:46
  • I believe you are using it correctly, but you can see Enum Converter example here: stackoverflow.com/questions/14279602/… Commented Mar 18, 2017 at 11:57
  • @RicardoSerra That answer shows a binding value converter, which should not be confused with a type converter. However, no binding is involved here. Commented Mar 18, 2017 at 12:04
  • Thanks @Clemens. Simply writing Value="Block" works and my control is rendered correctly in the design window. I had presumed that I need to define my own TypeConverter to get this functionality. Commented Mar 18, 2017 at 12:20

1 Answer 1

8

WPF already provides built-in type conversion from string to enum types.

So you could simply write

<Trigger Value="Block" ...> 
Sign up to request clarification or add additional context in comments.

3 Comments

If you rename the enum value, this will break :(
My point is it would be great to have an equivalent to nameof(). Using string is dangerous.
Maybe, but tell that Microsoft, not us. We can't do much about that.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.