问题
I'm trying to make a program to parse xml files with predefined format, and add some UI controls to my MainPage in Windows Universal Application.
In some part, I need to specify the background color of my TextBlocks in related xml file, so I'm looking for a way to convert string attribute, read from xml and convert it to Windows.UI.Color corresponding value.
here is my xml file and my C# code to add control
xml :
<test-unit name ="FOG_LAMP" text ="Fog Lamp" mode ="DIG_IN" color="ORANGE"/>
C#:
public void AddNewTextBlock(String Name, String Text, String Color)
{
TextBlock NewTextBlock = new TextBlock();
NewTextBlock.Name = Name;
NewTextBlock.Text = Text;
NewTextBlock.FontSize = 24;
myGrid.Children.Add(NewTextBlock);
}
Thanks For Help
回答1:
You can use XamlBindingHelper to convert the string
value to Color
-
var color = (Color)XamlBindingHelper.ConvertValue(typeof(Color), "ORANGE");
var brush = new SolidColorBrush(color);
NewTextBlock.Foreground = brush;
回答2:
Use Colors Helper of UWPCommunityToolkit.
Color redColor = "Red".ToColor();
Color redColor = ColorHelper.ToColor("#ff3a4ab0"); //For Alpha code
来源:https://stackoverflow.com/questions/44860768/converting-string-type-to-windows-ui-color-in-windows-universal-app