首页 > 解决方案 > 设置 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}"有什么不同?

不是每个人都提到窗口类型吗?

标签: wpfwpf-style

解决方案


只需在样式中指定目标类型,样式就会自动应用于您为其定义的类型的所有对象。但是,这不适用于基类。

在您的示例中,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>

推荐阅读