WPF用户控件样式

5 wpf user-controls styles

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

我试过了

<style TargetType={x:Type UserControl}>
    <setter property="Background" Value="Red" />
</style>
Run Code Online (Sandbox Code Playgroud)

它编译但不起作用.

任何的想法?谢谢!

Nir*_*Nir 22

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

<Window.Resources>
    <Style TargetType="{x:Type UserControl}">
        <Setter Property="Background" Value="Red" />
    </Style>
</Window.Resources>
<Grid>
    <UserControl Name="control" Content="content"></UserControl>
</Grid>
Run Code Online (Sandbox Code Playgroud)

但是这没有(创建一个派生自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>
Run Code Online (Sandbox Code Playgroud)

你可以做的是使用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>
Run Code Online (Sandbox Code Playgroud)

或者为每个派生类创建一个样式,您可以使用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>
Run Code Online (Sandbox Code Playgroud)


Nic*_*ski 3

我认为您缺少一些双引号:

尝试这个:

<Window.Resources>
    <Style TargetType="{x:Type UserControl}">
        <Setter Property="Background" Value="Red" />
    </Style>
</Window.Resources>
<Grid>
    <UserControl Name="control" Content="content"></UserControl>
</Grid>
Run Code Online (Sandbox Code Playgroud)