wpf - 在 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 文件中是可行的,但这不是我想要做的。
解决方案
尝试将按钮样式添加到 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>
推荐阅读
- python - Pandas - 检查列表列中的所有元素是否在另一个列表中
- swift - 为什么使用字符串插值比在表达式中使用 nil-coalescing 编译速度更快?
- reactjs - 每个 React Native 的 API Fetch - 与浏览器相比不同的终端日志
- security - 能否在 Outlook 365 中禁用 MAPI?
- redirect - 调用重定向的 websphere 应用程序服务器会导致创建新会话
- python - 如何在python3中以二进制模式将多个数据类型的值保存在.txt文件中?
- javascript - Shadow Dom 支持制表符表
- google-cloud-platform - 将 GCP Cloud IAM 自定义角色的访问权限仅限于存储桶
- css - 在 Angular (CSS) 中使用网格
- facebook-graph-api - 有没有办法使用 facebook API 获取用户的工作历史记录?