WPF绑定以更改椭圆的填充颜色

use*_*382 9 c# wpf xaml binding ellipse

可能是一个简单的问题但是:

如何以编程方式更改基于变量在XAML中定义的椭圆的颜色?

我读到的关于绑定的所有内容都基于集合和列表 - 我不能简单地(和字面上)基于字符串变量的值来设置它吗?string color ="red"color ="#FF0000"

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的评论):你不需要明确地使用TypeConverterin 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将字符串转换为画笔.


Lei*_*h S 6

您需要做的是实现自定义转换器将颜色转换为画笔对象.像这样......

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 }"