VS2022设计器中XAML Window自定义样式无法生效求助
问题描述
我给WPF的Window定义了如下样式,程序运行时样式能正常生效,但Visual Studio 2022的XAML设计器里就是不显示这个Window样式,其他像Button、Label这类控件的样式都能正常显示。
<Window x:Class="App.GUI.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="Main window" Height="350" Width="500" WindowStyle="None" Style="{DynamicResource WindowStyle2}" > <Window.Resources> <Style x:Key="WindowStyle2" TargetType="{x:Type Window}"> <Setter Property="WindowStyle" Value="None"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type Window}"> <Grid Background="LightSkyBlue"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <Button Background="Red" Content="X" Grid.Row="0"/> <ContentPresenter Grid.Row="1"/> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style> </Window.Resources> <Grid> <Button Content="xButton" HorizontalAlignment="Left" Margin="203,153,0,0" VerticalAlignment="Top"/> </Grid> </Window>
解决办法
试试下面这些方案:
- 换成StaticResource绑定:把Window的
Style="{DynamicResource WindowStyle2}"改成Style="{StaticResource WindowStyle2}"。设计器对StaticResource的解析优先级更高,更容易在设计时加载出来。 - 把样式移到全局资源里:把
WindowStyle2样式从当前Window的Window.Resources挪到App.xaml的Application.Resources中。全局资源在应用启动时就会加载,设计器能更稳定地识别到。 - 清理重启设计器:关掉当前的XAML设计器窗口,右键项目选“清理解决方案”,重新生成项目后再打开设计器。也可以直接重启Visual Studio,解决缓存导致的加载异常。
- 更新或修复VS:如果是设计器本身的bug,把Visual Studio 2022更到最新版本,或者通过VS安装器选择“修复”选项,修复损坏的设计器组件。
- 指定设计时样式:在Window标签里加
d:DesignStyle="{StaticResource WindowStyle2}",明确告诉设计器在设计模式下用这个样式,示例:
<Window x:Class="App.GUI.MainWindow" ... Style="{DynamicResource WindowStyle2}" d:DesignStyle="{StaticResource WindowStyle2}">
内容的提问来源于stack exchange,提问作者Ruslan
相关产品推荐
相关产品推荐

