Reputation:
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
Upvotes: 4
Views: 4891
Reputation: 5764
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"));
Upvotes: 6
Reputation: 8597
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");
Upvotes: 6
Reputation: 83
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
Upvotes: 0