I have to bind the gradient color property. In this I am using a converter. Here is the xaml code for binding
<GradientStop Color="{Binding Namevalue, RelativeSource={RelativeSource TemplatedParent}, Converter={StaticResource nametocolorconverter}}"/>
the code for nametocolorconverter
class nametocolorconverter: IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
Brush brw = new Brush();
if(value == "Blue") brw = Colors.Blue;
elseif(value=="Green") brw = Colors.Green;
else brw=Colors.Red;
return brw;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return null;
}
The above code is not working. I am not getting the desired color.
Your code does not even compile.
In the Convert method you declare a local variable brw
of type Brush
and try to create a new Brush
instance. Besides that this won't work because Brush
is an abstract class, you should instead have a variable of type Color
:
Color color;
if (value == "Blue")
{
color = Colors.Blue;
}
else if (value == "Green")
{
color = Colors.Green;
}
else
{
color = Colors.Red;
}
You may also use a switch statement instead of an if-else chain:
switch ((string)value)
{
case "Blue":
color = Colors.Blue;
break;
case "Green":
color = Colors.Green;
break;
default:
color = Colors.Red;
break;
}
Or even simpler, if you use only standard color names:
return (Color)ColorConverter.ConvertFromString((string)value);
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.