I need to convert string to color because color come dynamically as a string.
Error said :
Cannot implicity convert string to Xamarin.Form.Color
string BackgroundColor = (string)testData["Views"][index][name][i]["BackgroundColor"];
gridLayout.BackgroundColor = BackgroundColor;//Error
You can use Xamarin.Forms.ColorTypeConverter .
This method: ConvertFrom
Example from link:
var converter = new ColorTypeConverter ();
Assert.True (converter.CanConvertFrom (typeof(string)));
Assert.AreEqual (Color.Blue, converter.ConvertFrom ("Color.Blue"));
Assert.AreEqual (Color.Blue, converter.ConvertFrom ("Blue"));
Assert.AreEqual (Color.Blue, converter.ConvertFrom ("#0000ff"));
Assert.AreEqual (Color.Default, converter.ConvertFrom ("Color.Default"));
Assert.AreEqual (Color.Accent, converter.ConvertFrom ("Accent"));
var hotpink = Color.FromHex ("#FF69B4");
Color.Accent = hotpink;
Assert.AreEqual (Color.Accent, converter.ConvertFrom ("Accent"));
I suppose your string is a hex value of the color you want to apply. If so you must parse it as a color. The .setBackground
method and BackgroundColor
property accepts a color object.
To parse it, use the Color
class which contains FromHex
method.
Color.FromHex("#FFF");
You can convert string to color using ColorTypeConverter
var converter = new ColorTypeConverter ();
gridLayout.BackgroundColor = converter.ConvertFrom ("Color.Blue");
gridLayout.BackgroundColor = converter.ConvertFrom ("Blue");
gridLayout.BackgroundColor = converter.ConvertFrom ("#0000ff");
Hope this helps
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.