【问题标题】:Setting styles for subcontrols of usercontrol为 usercontrol 的子控件设置样式
【发布时间】:2011-09-23 09:56:03
【问题描述】:

假设我有一个这样的用户控件:

<UserControl x:Class="StyleTest.UserControl1"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d" 
         d:DesignHeight="300" d:DesignWidth="300">
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition />
        <RowDefinition />
    </Grid.RowDefinitions>
    <Button Grid.Row="0">Style please</Button>
    <Button Grid.Row="1">Style please</Button>
</Grid>

我想将此控件中的所有按钮设置为背景=绿色。 但是我不想影响程序中的其他按钮,也不想修改控件的代码。

我现在发现的是这样的:

<Window x:Class="StyleTest.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:loc="clr-namespace:StyleTest"
    Title="MainWindow" Height="350" Width="525">
<Window.Resources>
    <Style x:Key="UserControlStyles" TargetType="Button">
        <Setter Property="Background" Value="green" />
    </Style>
</Window.Resources>
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition />
        <ColumnDefinition />
    </Grid.ColumnDefinitions>
    <Button Grid.Column="0">no Style please</Button>
    <loc:UserControl1 Grid.Column="1">
        <loc:UserControl1.Resources>
            <Style TargetType="Button" BasedOn="{StaticResource UserControlStyles}" />
        </loc:UserControl1.Resources>
    </loc:UserControl1>
</Grid>

但这意味着我必须将此代码添加到控件的每个实例,以及一些额外的代码,如果我想设置样式,例如文本框的前景色也是。

我正在寻找的是类似于这样的东西:

        <Style TargetType="Buttons that are childs of UserControl1">
        <Setter Property="Background" Value="green" />
    </Style>

有没有办法做到这一点?

我不认为一个控件模板就足够了,因为我不想重新设计整个控件,我只想设置按钮的颜色。

【问题讨论】:

    标签: wpf xaml styles


    【解决方案1】:

    在 App.xaml 中,您可以添加此样式,该样式将应用于 UserControl1 的所有实例

    <Style TargetType="StyleTest:UserControl1" >
       <Style.Resources>
         <Style TargetType="Button">
            <Setter Property="Background" Value="green" />
         </Style>
       </Style.Resources>
    </Style>
    

    【讨论】:

    • 谢谢,这正是我要找的。​​span>
    【解决方案2】:

    如果我理解正确,你只需要修改你的 UserControl 以便在那里添加样式,而不是在窗口控件中

    <UserControl x:Name=UserControl1 ...>
    <UserControl.Resources>
       <Style TargetType="Button">
            <Setter Property="Background" Value="green" />
       </Style>
    </UserControl.Resources>
    

    我刚刚看到你说你不想修改控件。你的意思是你不能修改UserControl的xaml?为什么不呢?

    【讨论】:

    • 这或多或少是我现在正在做的事情。但我不想将此代码添加到此控件的每次使用中。我希望有一个中心位置(app.xaml)来设置这种类型的所有控件中所有按钮的样式。
    • @MTR:这不是针对控件的所有用法,只是在控件定义中。
    • 我明白了。但是我不想修改控件的代码,因为它被其他程序使用了。
    猜你喜欢
    • 1970-01-01
    • 2011-03-23
    • 1970-01-01
    • 1970-01-01
    • 2014-01-07
    • 1970-01-01
    • 2021-12-23
    • 2012-02-21
    • 2023-04-05
    相关资源
    最近更新 更多