【发布时间】:2016-05-12 20:37:50
【问题描述】:
我尝试运行示例,类似于 Charles Petzold 在其speech 中演示的示例,但不幸的是,我无法让 TextBlock 的 Foreground 属性接受我的自定义 MarkupExtension,它只返回一个颜色:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication1"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<StackPanel >
<TextBlock Foreground="{local:MyConverter}"
Text="{Binding Source={x:Reference slider},
Path=Value,
StringFormat='Rotation = {0:F2} degree'}">
</TextBlock>
<Slider x:Name="slider" Minimum="-360" Maximum="360"></Slider>
</StackPanel>
</Window>
使用以下简单的标记扩展:
class MyConverter : MarkupExtension
{
public override object ProvideValue(IServiceProvider serviceProvider)
{
return System.Drawing.Color.Red;
}
}
在启动应用程序时,我收到一个带有内部异常的 XamlParseException,它指出:{"'Color [Red]' is not a valid value for property 'Foreground'."} em>
我也尝试过返回实心画笔:return new SolidBrush(Color.Red);,但效果相同。我究竟做错了什么?以及如何让我的 Foreground 属性接受颜色对象作为值?我需要再转换成字符串吗?
【问题讨论】:
-
Foreground不是System.Media.Brushes类型的吗? -
因为它使用画笔
标签: c# wpf xaml user-interface markup-extensions