这是一个完全可重现的示例:
<Window x:Class="DemoWPF.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"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid Name="GridMain">
<Grid.Resources>
<Style x:Key="{x:Type Grid}">
<Setter Property="Control.Background" Value="Red"/>
</Style>
</Grid.Resources>
<StackPanel>
<Label>First Content</Label>
<TextBox>First Edit</TextBox>
<StackPanel>
<Label>Second Content</Label>
<TextBox>Second Edit</TextBox>
</StackPanel>
</StackPanel>
</Grid>
</Window>
我感到困惑的是,该TextBox
控件具有一个BackgroundProperty
继承自Control
-的控件,与没什么不同Label
。但是,可以看出TextBox
es的背景色没有改变。尽管Grid
没有Control.Background
属性,但是具有Panel.Background
属性,但是即使设置的属性是,也仍然设置了其背景属性Control.Background
。
我感到困惑的是,TextBox类具有从控件继承的BackgroundProperty-与Label没什么不同。但是,可以看出,TextBox的背景色没有更改。
每个控件都有一个默认样式和控件模板。它们定义了控件的必需部分,外观和视觉状态。的Background
是,其中一个属性可以或可以不被限定,这取决于控制。对于您使用的控件,背景的定义如下:
Label
: Transparent
TextBox
: SystemColors.WindowBrushKey
Grid
:无,默认值。StackPanel
:无,默认值。因此,Label
看起来是红色,但不是。通过背景可以看到的是StackPanel
或背景。对于,背景不会因依赖项属性设置优先级而改变。默认隐式样式的背景值Just优先于本地样式设置器。Grid
Transparent
TextBox
TextBox
现在做什么?为背景分配更高的优先级,例如:
将其添加为本地值。
定义样式并将其直接分配给的Style
属性TextBox
。
为定义隐式样式 TextBox
<Style x:Key="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}">
<Setter Property="Control.Background" Value="Red"/>
</Style>
尽管Grid没有
Control.Background
属性,但是具有Panel.Background
属性,但是即使设置的属性是,它仍然具有其背景属性设置Control.Background
。
这是WPF中的另一个实现细节。如您在的参考源中所Panel
看到的,它定义了Background
属性,但是当您查看的参考源时Control
,您可以看到它没有定义Background
属性本身,而是将自身添加为定义的属性的所有者Panel
。从以下文档中AddOwner
:
通常,AddOwner用于将依赖项属性添加到尚未通过托管类继承公开该依赖项属性的类(类继承将导致包装器属性被派生类继承,因此将提供对依赖属性)。AddOwner使属性系统能够识别最初没有注册该依赖项属性的类型的依赖项属性。
换句话说,这些属性的工作就像继承它们一样,并且XAML处理器足够聪明,可以识别Control.Background
和Panel.Background
属性基本相同。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句