资源库属性背景不会更改 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我的依赖项属性将在其中。因为知道它只是从控制派生:

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>

如果不让我知道,这可能真的有效。

最新更新