Свойство setter background не меняет цвет фона в WPF - PullRequest
0 голосов
/ 03 октября 2018

У меня есть PerformanceMeterStyle.xaml с одним свойством, которое устанавливает желтый цвет фона:

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

Затем у меня есть PerformanceMeter.cs, куда входит мое свойство зависимости. Ибо знаю, что оно просто происходит от Control:

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

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

В моем MainWindow.xaml я использую созданный мной элемент управления:

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

Почему цвет фона моего элемента управления не меняется на свойство, заданное в PerformanceMeterStyle.xaml?

1 Ответ

0 голосов
/ 05 октября 2018

Вы должны создать шаблон управления для этого следующим образом:

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

Это может сработать, если не сообщите мне.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...