WPF绑定改变椭圆填充颜色 [英] WPF Binding to change fill color of ellipse
问题描述
可能是一个简单的问题,但:
Probably a simple question but:
如何编程更改在XAML基于变量定义的椭圆的颜色
How do I programmatically change the color of an ellipse that is defined in XAML based on a variable?
一切我已经在绑定是以收藏,并列出我难道不会基于一个字符串变量的值设置它只是(和字面)读?串色=红颜色=#FF0000
Everything I've read on binding is based on collections and lists -can't I set it simply (and literally) based on the value of a string variable? string color = "red" color = "#FF0000"
推荐答案
值得指出的是,转换器中的其他职位中引用的已存在的,这就是为什么你可以做<摆在首位
在XAML;椭圆填充=红过夜。该转换器是 System.Windows.Media.BrushConverter
:
It's worth pointing out that the converter the other posts reference already exists, which is why you can do <Ellipse Fill="red">
in xaml in the first place. The converter is System.Windows.Media.BrushConverter
:
BrushConverter bc = new BrushConverter();
Brush brush = (Brush) bc.ConvertFrom("Red");
的更有效的方法是使用完整的语法:
The more efficient way is to use the full syntax:
myEllipse.Fill = new SolidColorBrush(Colors.Red);
修改回应-1和评论:
上面的代码工作完全正常的代码的,这是原来的问题是问。您还的不的希望有一个的IValueConverter
- 这些通常用于的结合的场景。 A 的TypeConverter
在这里是正确的解决方案(因为你是单向的字符串转换为刷)。请参见详情这篇文章。
The code above works perfectly fine in code, which is what the original question was asking about. You also don't want an IValueConverter
- these are typically used for binding scenarios. A TypeConverter
is the right solution here (because you're one-way converting a string to a brush). See this article for details.
进一步修改(已重读阿维亚德的评论):你不需要在XAML中明确使用的TypeConverter
- 这是用于你。如果我写这篇文章在XAML:
Further edit (having reread Aviad's comment): you don't need to explicitly use the TypeConverter
in Xaml - it's used for you. If I write this in Xaml:
<Ellipse Fill="red">
...那么运行时自动地使用 BrushConverter
打开字符串成一刷。这一XAML是基本上转变成等价的普通写法:
... then the runtime automagically uses a BrushConverter
to turn the string literal into a brush. That Xaml is essentially converted into the equivalent longhand:
<Ellipse>
<Ellipse.Fill>
<SolidColorBrush Color="#FFFF0000" />
</Ellipse.Fill>
</Ellipse>
所以,你是对的 - 你不能在XAML中使用它 - 但你并不需要到
So you're right - you can't use it in Xaml - but you don't need to.
即使你有你的作为填充想要的绑定的字符串值,你并不需要指定转换器手动。本次测试从Kaxaml:
Even if you had a string value that you wanted to bind in as the fill, you don't need to specify the converter manually. This test from 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的山坳
,仍然有这项工作 - 但与它结合,并自动使用 ValueConverter
转串入一个刷子
Strangely, you can't just use the StaticResource col
and still have this work - but with the binding it and automatically uses the ValueConverter
to turn the string into a brush.
这篇关于WPF绑定改变椭圆填充颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!