c# - 设置 WPF 用户控件的样式

标签 c# wpf user-controls

我知道我可以通过添加属性在控件中设置 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}"/>

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

然而,这只设置了 UserControlBackground,所以我如何将相同的背景应用到它的组件。

如何使用 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/

相关文章:

c# - MVC 5 项目中的 Entity Framework 6.0 不工作

c# - SignalR OnConnected - 向连接的客户端发送消息

c# - 使用 PushSharp 推送通知 - 基础知识

wpf - 更改 UserControl 文件中的命名空间后,...g.cs 文件出现错误

c# - 命名空间中的 URL 引用,它们是如何工作的?

c# - 如何更新异步获取的 View 模型属性?

javascript - 使用纯 Javascript 显示/隐藏组合框下拉列表

c# - 使用两个 View 并在 View 之间切换

c# - ASP.NET WebForms 自定义 UserControl - base.SaveViewState() 返回 null - 为什么?

c# - 多选 WinForms 列表框的双向绑定(bind)?