簡體   English   中英

設置屬性背景不會更改WPF中的背景顏色

[英]setter property background doesn't change the background color in WPF

我有一個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中設置的屬性?

您應該為此創建控件模板,如下所示:

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

如果不讓我知道,這實際上可能有效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM