我知道我可以通过添加属性在控件中设置 UserControl
的样式:
Style="{StaticResource MyStyle}"
并且在我的 ResourceDictionary
中有一个样式如下所示:
<Style x:Key="MyStyle" TargetType="{x:Type UserControl}">
<Style.Resources>
<Style TargetType="Label">
<!-- Label Setters -->
</Style>
<Style TargetType="TextBox">
<!-- TextBox Setters -->
</Style>
</Style.Resources>
</Style>
但有没有一种方法可以直接在 ResourceDictionary
中设置 UserControl
的样式,例如:
<Style x:Key="MyStyle" TargetType="{x:Type MyControl}">
基本上我的问题是,我可以将样式直接应用到控件而不是控件组件吗?
编辑: 我想要完成的是类似以下内容:
<Style x:Key="MyStyle" TargetType="{x:Type MyControl}">
<Setter Property="Background" Value="Black"/>
</Style>
<Style x:Key="{x:Type MyControl}" TargetType="{x:Type MyControl}" BasedOn="{StaticResource MyStyle}"/>
第二行将样式应用于应用程序中的所有控件,如果您对普通控件执行类似的操作,则此方法有效。
然而,这只设置了 UserControl
的 Background
,所以我如何将相同的背景应用到它的组件。
如何使用 UserControl
来实现?
最佳答案
您可以像这样直接设置用户控件的样式:
<UserControl x:Class="MyNamespace.MyControl" xmlns:local="MyNamespace" ...>
<UserControl.Style>
<Style>
<Setter Property="local:MyControl.MyProperty" Value="..."/>
...
</Style>
</UserControl.Style>
</UserControl>
或者像这样:
<UserControl x:Class="MyNamespace.MyControl" xmlns:local="MyNamespace" ...>
<UserControl.Style>
<Style TargetType="local:MyControl">
<Setter Property="MyProperty" Value="..."/>
...
</Style>
</UserControl.Style>
</UserControl>
UserControl 资源中的默认样式也应该有效:
<UserControl x:Class="MyNamespace.MyControl" xmlns:local="MyNamespace" ...>
<UserControl.Resources>
<Style TargetType="local:MyControl">
<Setter Property="MyProperty" Value="..."/>
...
</Style>
</UserControl.Resources>
</UserControl>
关于c# - 设置 WPF 用户控件的样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36082315/