如何设置背景颜色?

时间:2016-08-18 09:00:45

标签: c# wpf xaml

我从互联网复制了基于单元的文本框类,类定义如下:

git gc --prune=today

我按照以下方式插入xaml窗口:

using System;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace SapQmWp.Classes
{
  public class UnitTextBox : TextBox
  {
    public static DependencyProperty UnitTextProperty =
      DependencyProperty.Register(
        "UnitText",
        typeof(string),
        typeof(UnitTextBox),
        new FrameworkPropertyMetadata(
          default(string),
          FrameworkPropertyMetadataOptions.AffectsMeasure |
          FrameworkPropertyMetadataOptions.AffectsArrange |
          FrameworkPropertyMetadataOptions.AffectsRender));

    public static DependencyProperty UnitPaddingProperty =
      DependencyProperty.Register(
        "UnitPadding",
        typeof(Thickness),
        typeof(UnitTextBox),
        new FrameworkPropertyMetadata(
          new Thickness(5d, 0d, 0d, 0d),
          FrameworkPropertyMetadataOptions.AffectsMeasure |
          FrameworkPropertyMetadataOptions.AffectsArrange |
          FrameworkPropertyMetadataOptions.AffectsRender));

    public static DependencyProperty TextBoxWidthProperty =
      DependencyProperty.Register(
        "TextBoxWidth",
        typeof(double),
        typeof(UnitTextBox),
        new FrameworkPropertyMetadata(
          double.NaN,
          FrameworkPropertyMetadataOptions.AffectsMeasure));

    private FormattedText _unitText;
    private Rect _unitTextBounds;

    public string UnitText
    {
      get { return (string) GetValue(UnitTextProperty); }
      set { SetValue(UnitTextProperty, value); }
    }

    public Thickness UnitPadding
    {
      get { return (Thickness) GetValue(UnitPaddingProperty); }
      set { SetValue(UnitPaddingProperty, value); }
    }

    public double TextBoxWidth
    {
      get { return (double) GetValue(TextBoxWidthProperty); }
      set { SetValue(TextBoxWidthProperty, value); }
    }

    protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
    {
      base.OnPropertyChanged(e);

      if (e.Property == ForegroundProperty)
        EnsureUnitText(true);
    }

    protected override Size MeasureOverride(Size constraint)
    {
      var textBoxWidth = TextBoxWidth;
      var unit = EnsureUnitText(true);
      var padding = UnitPadding;

      if (unit != null)
      {
        var unitWidth = unit.Width + padding.Left + padding.Right;
        var unitHeight = unit.Height + padding.Top + padding.Bottom;

        constraint = new Size(
          constraint.Width - unitWidth,
          Math.Max(constraint.Height, unitHeight));
      }

      var hasFixedTextBoxWidth = !double.IsNaN(textBoxWidth) &&
                                 !double.IsInfinity(textBoxWidth);

      if (hasFixedTextBoxWidth)
        constraint = new Size(textBoxWidth, constraint.Height);

      var baseSize = base.MeasureOverride(constraint);
      var baseWidth = hasFixedTextBoxWidth ? textBoxWidth : baseSize.Width;

      if (unit != null)
      {
        var unitWidth = unit.Width + padding.Left + padding.Right;
        var unitHeight = unit.Height + padding.Top + padding.Bottom;

        return new Size(
          baseWidth + unitWidth,
          Math.Max(baseSize.Height, unitHeight));
      }

      return new Size(baseWidth, baseSize.Height);
    }

    protected override Size ArrangeOverride(Size arrangeBounds)
    {
      var textSize = arrangeBounds;
      var unit = EnsureUnitText(false);
      var padding = UnitPadding;

      if (unit != null)
      {
        var unitWidth = unit.Width + padding.Left + padding.Right;
        var unitHeight = unit.Height + padding.Top + padding.Bottom;

        textSize.Width -= unitWidth;

        _unitTextBounds = new Rect(
          textSize.Width + padding.Left,
          (arrangeBounds.Height - unitHeight)/2 + padding.Top,
          textSize.Width,
          textSize.Height);
      }

      var baseSize = base.ArrangeOverride(textSize);

      if (unit != null)
      {
        var unitWidth = unit.Width + padding.Left + padding.Right;
        var unitHeight = unit.Height + padding.Top + padding.Bottom;

        return new Size(
          baseSize.Width + unitWidth,
          Math.Max(baseSize.Height, unitHeight));
      }

      return baseSize;
    }

    protected override void OnRender(DrawingContext drawingContext)
    {
      base.OnRender(drawingContext);
      var unitText = EnsureUnitText(false);
      if (unitText != null)
        drawingContext.DrawText(unitText, _unitTextBounds.Location);
    }

    private FormattedText EnsureUnitText(bool invalidate = false)
    {
      if (invalidate)
        _unitText = null;

      if (_unitText != null)
        return _unitText;

      var unit = UnitText;

      if (!string.IsNullOrEmpty(unit))
      {
        _unitText = new FormattedText(
          unit,
          CultureInfo.InvariantCulture,
          FlowDirection,
          new Typeface(
            FontFamily,
            FontStyle,
            FontWeight,
            FontStretch),
          FontSize,
          Foreground);
      }

      return _unitText;
    }
  }
}

但背景颜色为空而不是颜色 enter image description here

我的问题,如何为UnitText设置背景颜色?

更新

...
<ui:UnitTextBox Grid.Row="1" Style="{StaticResource WeightTbStyle}" UnitText="KG" Text="{Binding TargetWeight, UpdateSourceTrigger=PropertyChanged}"/>
...

更新2
当我在像

这样的控件上设置背景时
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:SapQmWp.Themes">

  <Style x:Key="WeightTbStyle" TargetType="TextBox">
    <Setter Property="Background" Value="#F8F8F8" />
    <Setter Property="BorderBrush" Value="{x:Null}"/>
    <Setter Property="Margin" Value="10,40,10,40" />
    <Setter Property="Padding" Value="0,0,0,5" />
    <Setter Property="HorizontalContentAlignment" Value="Center" />
    <Setter Property="VerticalContentAlignment" Value="Center" />
    <Setter Property="Foreground" Value="#404242"/>
    <Setter Property="FontSize" Value="24pt"/>
    <Setter Property="FontWeight" Value="Bold"/> 
    <Setter Property="BorderThickness" Value="0" />
  </Style>


</ResourceDictionary>

结果我得到了:
enter image description here

1 个答案:

答案 0 :(得分:0)

在你的

protected override void OnRender(DrawingContext drawingContext)
    {
      base.OnRender(drawingContext);
      var unitText = EnsureUnitText(false);
      if (unitText != null)
        drawingContext.DrawText(unitText, _unitTextBounds.Location);
    }

尝试这样的设置颜色和格式

        var formattedText = new FormattedText(unitText,
            CultureInfo.CurrentCulture,
            FlowDirection.LeftToRight,
            new Typeface(new FontFamily("ANY_FONT_FAMILY"), FontStyles.Normal, FontWeights.Bold, FontStretches.Normal),
            24, Brushes.Red);

        drawingContext.DrawText(formattedText, _unitTextBounds.Location);
    }

对于背景颜色,只需在渲染文本之前绘制一个矩形。

drawingContext.DrawRectangle(Brushes.Red, Nothing, YOUR_TEXT_RECT);