简体   繁体   中英

setter property background doesn't change the background color in WPF

I have a PerformanceMeterStyle.xaml with one property that set's the background to yellow:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                        xmlns:controls="clr-namespace:TemplateLearn.Controls">
        <Style TargetType="controls:PerformanceMeter" x:Key="PerformanceMeterStyle">
            <Setter Property="Background" Value="Yellow"/>
        </Style>
</ResourceDictionary>

Then I have PerformanceMeter.cs where my dependency property's will come in. For know it just derives from Control:

using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace TemplateLearn.Controls
{
    public class PerformanceMeter : Control
    {
    }
}

In my MainWindow.xaml i use my created control:

<Window x:Class="TemplateLearn.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:TemplateLearn"
        xmlns:controls="clr-namespace:TemplateLearn.Controls"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">

  <Window.Resources>
        <ResourceDictionary Source="Theme/Styles/PerformanceMeterStyle.xaml" />
  </Window.Resources>

  <controls:PerformanceMeter Style="{StaticResource PerformanceMeterStyle}"/>
</Window>

Why is the background color of my control not changing to the property I set in PerformanceMeterStyle.xaml?

you should create control template for that as follows:

<Style TargetType="controls:PerformanceMeter" x:Key="PerformanceMeterStyle">
            <Setter Property="Background" Value="Yellow" />
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type controls:PerformanceMeter}">
                        <Border x:Name="border"
                            Background="{TemplateBinding Background}">
                            <ContentPresenter />
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

This might actually work, if not let me know.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM