设置WPF UserControl的样式

The*_*der 8 c# wpf user-controls

我知道我可以UserControl通过添加属性在控件中设置类似的样式:

Style="{StaticResource MyStyle}"
Run Code Online (Sandbox Code Playgroud)

在我的风格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>
Run Code Online (Sandbox Code Playgroud)

但是,有没有办法,我可以设置的样式UserControlResourceDictionary直接,如:

<Style x:Key="MyStyle" TargetType="{x:Type MyControl}">
Run Code Online (Sandbox Code Playgroud)

基本上我的问题是,我可以直接将样式应用于控件而不是控件组件吗?

编辑: 我想要完成的是以下内容:

<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}"/>
Run Code Online (Sandbox Code Playgroud)

如果第二行将样式应用于应用程序中的所有控件,如果使用普通控件执行类似操作,则此方法有效.

然而,这只是设置BackgroundUserControl,所以我怎么可以应用相同的背景及其组件.

我该怎么办呢UserControl

Cle*_*ens 7

您可以像这样直接设置 UserControl 的样式:

<UserControl x:Class="MyNamespace.MyControl" xmlns:local="MyNamespace" ...>
    <UserControl.Style>
        <Style>
            <Setter Property="local:MyControl.MyProperty" Value="..."/>
            ...
        </Style>
    </UserControl.Style>
</UserControl>
Run Code Online (Sandbox Code Playgroud)

或者像这样:

<UserControl x:Class="MyNamespace.MyControl" xmlns:local="MyNamespace" ...>
    <UserControl.Style>
        <Style TargetType="local:MyControl">
            <Setter Property="MyProperty" Value="..."/>
            ...
        </Style>
    </UserControl.Style>
</UserControl>
Run Code Online (Sandbox Code Playgroud)

UserControl 资源中的默认样式也应该有效:

<UserControl x:Class="MyNamespace.MyControl" xmlns:local="MyNamespace" ...>
    <UserControl.Resources>
        <Style TargetType="local:MyControl">
            <Setter Property="MyProperty" Value="..."/>
            ...
        </Style>
    </UserControl.Resources>
</UserControl>
Run Code Online (Sandbox Code Playgroud)


slu*_*ter 3

您需要x:Key从定义的样式中删除 ,以便它可以普遍应用于与 中定义的类型相同的所有控件TargetType

引用 MSDN 中的Style.TargetType Property

将 TargetType 属性设置为 TextBlock 类型而不设置 x:Key 会隐式将 x:Key 设置为 {x:Type TextBlock}。这也意味着,如果您为 [...] 样式指定除 {x:Type TextBlock} 之外的任何 x:Key 值,则该样式不会自动应用于所有 TextBlock 元素。相反,您需要将样式显式应用于 TextBlock 元素。