WPF用户控制样式

WPF用户控制样式,wpf,user-controls,styles,Wpf,User Controls,Styles,我想设置我的项目的所有usercontrols的background属性 我试过了 <style TargetType={x:Type UserControl}> <setter property="Background" Value="Red" /> </style> 它可以编译,但不起作用 有什么想法吗? 谢谢 我想你遗漏了一些双引号: 试试这个: <Window.Resources> <Style TargetTy

我想设置我的项目的所有usercontrols的background属性

我试过了

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

它可以编译,但不起作用

有什么想法吗?
谢谢

我想你遗漏了一些双引号:

试试这个:

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

您只能将样式设置为特定类,因此这将起作用(创建UserControl对象,不是很有用):


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


您可以使用style属性显式设置样式:

<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避免重复样式内容:

<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中有两个样式选项。@Fëanor-x:Type有时是可选的
<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>
<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>