wpf - 设置 WPF 样式
问题描述
我在 wpf 中编写了一个 XAML 代码,我在 window.resource 中定义了这样的样式
<Window x:Class="WpfApp1.Test"
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:self="clr-namespace:WpfApp1"
xmlns:system="clr-namespace:System;assembly=mscorlib"
xmlns:local ="clr-namespace:WpfApp1"
mc:Ignorable="d"
Height="400 " Width="450" >
<Window.Resources>
<Style TargetType="{x:Type Window}">
<Setter Property="Title" Value="Hello my friens!"/>
</Style>
</Window.Resources>
<Grid>
</Grid>
在这里,Test 是我的窗口类名。当我运行时一切正常,但是当我在上面更改为这个时
<Window.Resources>
<Style TargetType="{x:Type Window}">
<Setter Property="Title" Value="Hello my friends!"/>
</Style>
</Window.Resources>
在设计窗口中,标题显示为Value="Hello my friends!" 但是当我运行应用程序时,标题变为空。这是怎么回事?顺便说一句TargetType="{x:Type Window}"和TargetType="{x:Type local:Test}"有什么不同?
不是每个人都提到窗口类型吗?
解决方案
只需在样式中指定目标类型,样式就会自动应用于您为其定义的类型的所有对象。但是,这不适用于基类。
在您的示例中,TargetType="{x:Type Window}"
将自动应用标题“Hello my friends!” 到所有窗户。但是,您的窗口类型不是Window
,而是WpfApp1.Test
。Window 只是使用的基类。这就是样式不会自动应用于窗口的原因。
如果您改用TargetType="{x:Type local:Test}"
它,它将自动应用于所有具有 type 的对象WpfApp1.Test
,这对您的窗口来说是正确的。样式的自动应用仅适用于特定类型,不适用于基类。
您还可以指定一个键属性,然后告诉您的窗口它应该使用这种样式。在这种情况下,您也可以使用x:Type Window
,因为这样会显式应用样式。例如:
<Window x:Class="WpfApp1.Test"
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:self="clr-namespace:WpfApp1"
xmlns:system="clr-namespace:System;assembly=mscorlib"
xmlns:local ="clr-namespace:WpfApp1"
mc:Ignorable="d"
Height="400 " Width="450" Style="{DynamicResource MyStyle}">
<Window.Resources>
<Style TargetType="{x:Type Window}" x:Key="MyStyle">
<Setter Property="Title" Value="Hello my friends!"/>
</Style>
</Window.Resources>
推荐阅读
- c# - HotChocolate 解析和异步
- mysql - 从 circle ci 访问 MySQL GCP 以自动化数据库迁移?
- time - 如何在Java中获取当前时间与偏移量?
- c - 为什么在 GDB 调试期间 C 空终止符 `\0` 显示为 `\000`?
- r - 如何将许多“chr”转换为具有有序水平的因子?
- touchscreen - PsychoPy 中的触摸屏
- amazon-web-services - 将 Glyphs 与 Amazon Location Service 和 Mapbox-GL 结合使用
- powershell - 带有 CMK 的 Azure 存储,通过电子邮件发送密钥轮换提醒
- ios - 使用 Xcode 和 Objective-c 的 iOS 应用程序后台未显示 userNotification
- c# - 将 BackGroundColor 更改为 CollectionView 的元素