theMaxx theMaxx - 11 months ago 105
C# Question

How to Set a Control's Property Using a String Variable in C# XAML WinRT?

How can I set the property for a XAML control using a string variable?

This is an example of the variable to be used.

string imageStretch = "Uniform";

How can it be set like this programmatically in the code behind?

myImage.Stretch = imageStretch;

The reason is that I would like to avoid using a long chunk of code like this.

if (imageStretch == "None") { myImage.Stretch = Stretch.None; }
if (imageStretch == "Fill") { myImage.Stretch = Stretch.Fill; }
if (imageStretch == "Uniform") { myImage.Stretch = Stretch.Uniform; }
if (imageStretch == "UniformToFill") { myImage.Stretch = Stretch.UniformToFill; }

If this can be done, can it be done for other types of controls/properties as well?

Answer Source

use enum.Parse() like such...

myImage.Stretch = (Stretch)Enum.Parse(typeof(Stretch), imageStretch);