Search code examples
c#wpfxamluser-interfacemarkup-extensions

Why does the TextBlock.Foreground property in XAML not accept a Color?


I've tried to run the samples, similar to the ones that Charles Petzold demonstrated in his speech, but unfortunately, I can't get the TextBlock's Foreground property to accept my custom MarkupExtension, which simply returns a Color:

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

with the following simply Markup-Extension:

class MyConverter : MarkupExtension
{
    public override object ProvideValue(IServiceProvider serviceProvider)
    {            
        return System.Drawing.Color.Red;
    }
}

Upon starting the application, I get a XamlParseException with an inner Exception that states: {"'Color [Red]' is not a valid value for property 'Foreground'."}

I've also tried returning a solid brush: return new SolidBrush(Color.Red);, but with the same effect. What am I doing wrong? And how can I get my Foreground property to accept a Color-object as value? Do I need another conversion into a string?


Solution

  • class MyConverter : MarkupExtension
    {
        public override object ProvideValue(IServiceProvider serviceProvider)
        {            
            return System.Media.Brushes.Red;
        }
    }
    

    I think TextBlock.ForeGround is of type System.Media.Brushes which contains similar base colors.