WPF 用户控件样式 [英] WPF UserControl Style

查看:45
本文介绍了WPF 用户控件样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想设置我项目的所有用户控件的背景属性.

I want to set the background property of all the usercontrols of my project.

我试过

<style TargetType={x:Type UserControl}>
    <setter property="Background" Value="Red" />
</style>

它编译但没有工作.

¿有什么想法吗?谢谢!

¿Any Idea? Thanks!

推荐答案

你只能为一个特定的类设置一个样式,这样就可以了(创建一个 UserControl 对象,不是很有用):

You can only set a a style to a specific class, so this will work (create a UserControl object, not very useful):

<Window.Resources>
    <Style TargetType="{x:Type UserControl}">
        <Setter Property="Background" Value="Red" />
    </Style>
</Window.Resources>
<Grid>
    <UserControl Name="control" Content="content"></UserControl>
</Grid>

但这不会(创建一个从 UserControl 派生的类):

But this doesn't (Create a class derived from UserControl):

<Window.Resources>
    <Style TargetType="{x:Type UserControl}">
        <Setter Property="Background" Value="Red" />
    </Style>
</Window.Resources>
<Grid>
    <l:MyUserControl Name="control" Content="content"></l:MyUserControl>
</Grid>

您可以做的是使用 Style 属性显式设置样式:

What you can do is either explicitly set the style using the Style property:

<Window.Resources>
    <Style TargetType="{x:Type UserControl}" x:Key="UCStyle">
        <Setter Property="Background" Value="Red" />
    </Style>
</Window.Resources>
<Grid>
    <l:MyUserControl Name="control" Content="content" Style="{StaticResource UCStyle}"></l:MyUserControl>
</Grid>

或者为每个派生类创建一个样式,可以使用BasedOn来避免重复样式内容:

or create a style for each derived class, you can use BasedOn to avoid duplicating the style content:

<Window.Resources>
    <Style TargetType="{x:Type UserControl}" x:Key="UCStyle">
        <Setter Property="Background" Value="Red" />
    </Style>
    <Style TargetType="{x:Type l:MyUserControl}" BasedOn="{StaticResource UCStyle}" />
</Window.Resources>
<Grid>
    <l:MyUserControl Name="control" Content="content"></l:MyUserControl>
</Grid>

这篇关于WPF 用户控件样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆