值得指出的是,其他帖子引用的转换器已经存在,这就是为什么你可以这样做<Ellipse Fill="red">
首先在 xaml 中。转换器是System.Windows.Media.BrushConverter
:
BrushConverter bc = new BrushConverter();
Brush brush = (Brush) bc.ConvertFrom("Red");
更有效的方法是使用完整语法:
myEllipse.Fill = new SolidColorBrush(Colors.Red);
EDIT回应-1和评论:
上面的代码工作得很好in code,这就是最初的问题所问的内容。你也don't想要一个IValueConverter
- 这些通常用于binding场景。 ATypeConverter
是这里正确的解决方案(因为您将字符串单向转换为画笔)。看本文 http://bryantlikes.com/SilverlightIValueConverterVsTypeConverter.aspx了解详情。
进一步编辑(重读了 Aviad 的评论):您不需要明确使用TypeConverter
在 Xaml 中 - 它为您所用。如果我在 Xaml 中这样写:
<Ellipse Fill="red">
...然后运行时自动使用BrushConverter
将字符串文字变成画笔。该 Xaml 本质上被转换为等效的普通写法:
<Ellipse>
<Ellipse.Fill>
<SolidColorBrush Color="#FFFF0000" />
</Ellipse.Fill>
</Ellipse>
所以你是对的 - 你不能在 Xaml 中使用它 - 但你不需要这样做。
即使您有一个想要的字符串值bind作为填充,您不需要手动指定转换器。来自 Kaxaml 的测试:
<Page
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:s="clr-namespace:System;assembly=mscorlib">
<Page.Resources>
<s:String x:Key="col">Red</s:String>
</Page.Resources>
<StackPanel>
<Ellipse Width="20" Height="20" Fill="{Binding Source={StaticResource col}}" />
</StackPanel>
</Page>
奇怪的是,你不能只使用StaticResource col
仍然有这项工作 - 但通过绑定它并自动使用ValueConverter
将绳子变成刷子。