【问题标题】:Why does the TextBlock.Foreground property in XAML not accept a Color?为什么 XAML 中的 TextBlock.Foreground 属性不接受颜色?
【发布时间】: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


【解决方案1】:
class MyConverter : MarkupExtension
{
    public override object ProvideValue(IServiceProvider serviceProvider)
    {            
        return System.Media.Brushes.Red;
    }
}

我认为TextBlock.ForeGround 属于System.Media.Brushes 类型,其中包含相似的基色。

【讨论】:

  • 我为颜色和画笔使用了错误的命名空间System.Drawing 而不是System.Windows.Media
【解决方案2】:

因为Foreground 不是Color 而是Brush

公共画笔前景{get;放; }

source

您可以使用转换器处理此问题或在此线程中寻找答案:How to convert color code into media.brush?

【讨论】:

    【解决方案3】:

    你可以试试这样的

    textBlock.Inlines.Add(new Run("Red") { Foreground = Brushes.Red });
    

    【讨论】:

      【解决方案4】:

      试试这个....

      class MyConverter : MarkupExtension
      {
          public override object ProvideValue(IServiceProvider serviceProvider)
          {
              return new SolidColorBrush(Colors.Red);
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多