[英]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.