首页 > 解决方案 > 在 CustomUserControl 中扩展父控件的默认样式不起作用

问题描述

我正在尝试扩展在自定义 UserControl 内的任何父控件中定义的控件的隐式样式。这似乎不像我预期的那样工作。

场景将是:在 MainWindow.xaml 中包含一个 ResourceDictionary,它定义了一个默认主题。比我想扩展在我的用户控件中的该主题中定义的基本样式。

我已经尝试过的:

拥有一个 MainWindow.xaml,它在其资源中定义了以下 DefaultStyle:

<Window x:Class="UserControl_Style_Inheritance.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:UserControl_Style_Inheritance"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
  <Window.Resources>
    <Style TargetType="{x:Type Button}" BasedOn="{StaticResource {x:Type Button}}">
      <Setter Property="Background" Value="Blue"></Setter>
    </Style>
  </Window.Resources>
  <Grid>
    <local:MyUserControl></local:MyUserControl>
  </Grid>
</Window>

并且有一个 MyUserControl.xaml,它应该扩展 MainWindow.xaml 定义的 DefaultStyle:

<UserControl x:Class="UserControl_Style_Inheritance.MyUserControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:UserControl_Style_Inheritance"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800">
  <UserControl.Resources>
    <Style TargetType="{x:Type Button}" BasedOn="{StaticResource {x:Type Button}}">
      <Setter Property="BorderBrush" Value="Red"></Setter>
    </Style>
  </UserControl.Resources>
  <Grid>
      <Button>Hello</Button> 
  </Grid>
</UserControl>

但是 MyUserControl 基于普通按钮样式,它具有灰色背景而不是 MainWindow.xaml 中定义的样式的蓝色背景。

我做错了什么,或者我在哪里思考错误的方向?

编辑:将默认样式放入 Application.xaml 文件中是可行的,但这不是我想要做的。

标签: wpfxaml

解决方案


尝试将按钮样式添加到 App.xaml:

<Application.Resources>
    <Style x:Key="BtnStyle" TargetType="{x:Type Button}" BasedOn="{StaticResource {x:Type Button}}">
        <Setter Property="Background" Value="Blue"></Setter>
    </Style>
</Application.Resources>

并像这样在您的 UserControl 中使用它:

<UserControl.Resources>
    <Style TargetType="{x:Type Button}" BasedOn="{StaticResource BtnStyle}"> 
        <Setter Property="BorderBrush" Value="Red"></Setter>
    </Style>
</UserControl.Resources>
<Grid>
    <Button>Hello</Button>
</Grid>

推荐阅读