2016-08-18 10 views
1

я скопировал блок на основе класса текстового поля из Интернета и определение класса выглядит следующим образом:Как установить цвет фона?

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

И я вставить в окно XAML следующим образом:

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

Но цвет фона равна нулю, а не цвет.
enter image description here

Мой вопрос, как установить цвет фона для UnitText тоже?

Update

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

Update 2
Когда я установить фон на элементы управления, как

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

в результате я получил:
enter image description here

+1

Поскольку UnitTextBox наследует от TextBox, не имеет ли это свойство фона, которое вы можете установить? –

+0

Итак, когда я устанавливаю свойство фона в значение «Фон =« Синий », он не влияет на цвет фона« UnitText ». –

+0

'' Попробуйте это или установите значение свойства фона в соответствующем стиле, о котором вы говорите. – ViVi

ответ

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); 
+0

yikes! Вы спрашивали цвет текста или цвет фона? проигнорируйте это Если я gt it wong – Muds

+0

, чтобы получить цвет фона, просто нарисуйте прямоугольник перед визуализацией текста – Muds

+0

'UnitText' должен занять цвет фона. Я показал его выше слева на' KG'. –

Смежные вопросы