Wpf 如何向已使用样式模板的窗口添加其他样式
当窗口样式已经使用下面的样式时,如何向其添加其他样式Wpf 如何向已使用样式模板的窗口添加其他样式,wpf,xaml,Wpf,Xaml,当窗口样式已经使用下面的样式时,如何向其添加其他样式 <Style x:Key="MyWindowStyle" TargetType="Window"> <Setter Property="Control.Background" Value="PaleGreen"/> <Setter Property="Window.Title" Value="Styled Window"/> </Style> 我
<Style x:Key="MyWindowStyle" TargetType="Window">
<Setter Property="Control.Background" Value="PaleGreen"/>
<Setter Property="Window.Title" Value="Styled Window"/>
</Style>
我该怎么做?我搞不懂语法。您可以定义MyWindowStyle2并使用它
<Style x:Key="MyWindowStyle2" TargetType="Window" BasedOn="{StaticResource MyWindowStyle}">
<Setter Property="BorderThickness" Value="3"/>
<Setter Property="BorderBrush" Value="Red"/>
</Style>
或
问题是,当您使用
staticresource
时,必须在使用之前初始化资源
在您的情况下,资源位于窗口内,因此在初始化窗口之前它不会被初始化
改用DynamicResource
,它将起作用:
<Window x:Class="Binding.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:Binding"
mc:Ignorable="d"
Style="{DynamicResource MyWindowStyle}"
Title="MainWindow" Height="450" Width="800">
<Window.Resources>
<Style x:Key="MyWindowStyle" TargetType="{x:Type Window}">
<Setter Property="Control.Background" Value="PaleGreen"/>
<Setter Property="Window.Title" Value="Styled Window"/>
<Setter Property="BorderThickness" Value="3"/>
<Setter Property="BorderBrush" Value="Red"/>
</Style>
</Window.Resources>
<StackPanel>
<Label Content="Test Window" />
</StackPanel>
</Window>
查看有关WPF资源的更多信息。谢谢,但我想在本地添加样式,如果我将此样式添加到同一窗口的资源中(在同一窗口中不可用),则此操作无效。但是,如果我将它添加到应用程序的资源中,它就会工作。我想在本地添加样式。你知道这可能吗?谢谢
<Style x:Key="MyWindowStyle2" TargetType="Window" BasedOn="{StaticResource MyWindowStyle}">
<Setter Property="BorderThickness" Value="3"/>
<Setter Property="BorderBrush" Value="Red"/>
</Style>
<Window x:Class="Binding.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:Binding"
mc:Ignorable="d"
Style="{DynamicResource MyWindowStyle}"
Title="MainWindow" Height="450" Width="800">
<Window.Resources>
<Style x:Key="MyWindowStyle" TargetType="{x:Type Window}">
<Setter Property="Control.Background" Value="PaleGreen"/>
<Setter Property="Window.Title" Value="Styled Window"/>
<Setter Property="BorderThickness" Value="3"/>
<Setter Property="BorderBrush" Value="Red"/>
</Style>
</Window.Resources>
<StackPanel>
<Label Content="Test Window" />
</StackPanel>
</Window>