C# setter属性背景不为';t更改WPF中的背景色
我有一个PerformanceMeterStyle.xaml,其中一个属性将背景设置为黄色:C# setter属性背景不为';t更改WPF中的背景色,c#,wpf,C#,Wpf,我有一个PerformanceMeterStyle.xaml,其中一个属性将背景设置为黄色: <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:contr
<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>
在my Main Window.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>
如果不让我知道,这实际上可能会起作用。是否确实正确导入了资源文件?如果您在Visual Studio中遇到任何此类错误,您可以检查“输出”窗口,或者尝试在该资源文件中为基本WPF控件(如按钮/文本块)定义简单样式,并尝试将其应用于窗口中的相应控件。将
控件:PerformanceMeter
C#和模板代码添加到问题中。代码中可能存在一些问题。您需要定义一个实际使用后台属性的ControlTemplate。看见
<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>