Dan*_*zey 17
值得指出的是,其他帖子引用的转换器已经存在,这就是为什么你可以<Ellipse Fill="red">
在xaml中首先做到的.转换器是System.Windows.Media.BrushConverter
:
BrushConverter bc = new BrushConverter();
Brush brush = (Brush) bc.ConvertFrom("Red");
Run Code Online (Sandbox Code Playgroud)
更有效的方法是使用完整的语法:
myEllipse.Fill = new SolidColorBrush(Colors.Red);
Run Code Online (Sandbox Code Playgroud)
编辑以回应-1和评论:
上面的代码在代码中运行得非常好,这是原始问题所要求的.您也不希望IValueConverter
- 这些通常用于绑定方案.A TypeConverter
是正确的解决方案(因为你是单向转换字符串到画笔).有关详细信息,请参阅此文
进一步编辑(重读Aviad的评论):你不需要明确地使用TypeConverter
in Xaml - 它就是你用的.如果我在Xaml中写这个:
<Ellipse Fill="red">
Run Code Online (Sandbox Code Playgroud)
...然后运行时自动使用a BrushConverter
将字符串文字转换为画笔.Xaml基本上转换成等效的手写:
<Ellipse>
<Ellipse.Fill>
<SolidColorBrush Color="#FFFF0000" />
</Ellipse.Fill>
</Ellipse>
Run Code Online (Sandbox Code Playgroud)
所以你是对的 - 你不能在Xaml中使用它 - 但你不需要.
即使您有一个要作为填充绑定的字符串值,也不需要手动指定转换器.来自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>
Run Code Online (Sandbox Code Playgroud)
奇怪的是,你不能只使用它StaticResource col
仍然有这项工作 - 但它与绑定它并自动使用ValueConverter
将字符串转换为画笔.
您需要做的是实现自定义转换器将颜色转换为画笔对象.像这样......
public class ColorToBrushConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
System.Drawing.Color col = (System.Drawing.Color)value;
Color c = Color.FromArgb(col.A, col.R, col.G, col.B);
return new System.Windows.Media.SolidColorBrush(c);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
SolidColorBrush c = (SolidColorBrush)value;
System.Drawing.Color col = System.Drawing.Color.FromArgb(c.Color.A, c.Color.R, c.Color.G, c.Color.B);
return col;
}
}
Run Code Online (Sandbox Code Playgroud)
然后在绑定中指定转换器
Fill="{Binding Colors.Red, Converter={StaticResource ColorToBrushConverter }"
归档时间: |
|
查看次数: |
61295 次 |
最近记录: |