【发布时间】: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>
有没有办法做到这一点?
我不认为一个控件模板就足够了,因为我不想重新设计整个控件,我只想设置按钮的颜色。
【问题讨论】: