[英]Binding Gradient color in wpf
I have to bind the gradient color property. 我必须绑定渐变颜色属性。 In this I am using a converter. 在此,我正在使用转换器。 Here is the xaml code for binding 这是绑定的xaml代码
<GradientStop Color="{Binding Namevalue, RelativeSource={RelativeSource TemplatedParent}, Converter={StaticResource nametocolorconverter}}"/>
the code for nametocolorconverter 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. 在Convert方法中,声明一个Brush
类型的局部变量brw
并尝试创建一个新的Brush
实例。 Besides that this won't work because Brush
is an abstract class, you should instead have a variable of type Color
: 除此之外,由于Brush
是一个抽象类,因此无法正常工作,您应该改用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语句代替if-else链:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.