假设我有这样的用户控件:
<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>
我想将此控件中的所有按钮设置为background = green。 但我不想影响我程序中的其他按钮,我不想修改控件的代码。
我现在发现的是:
<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>
但这意味着我必须将此代码添加到控件的每个实例,以及一些额外的代码,如果我想要设置样式,例如TextBoxes的前景色也是。
我正在寻找的是类似的东西:
<Style TargetType="Buttons that are childs of UserControl1">
<Setter Property="Background" Value="green" />
</Style>
有没有办法做到这一点?
我不认为控制模板就足够了,因为我不想重新设计整个控件,我只想设置按钮的颜色。
答案 0 :(得分:6)
在App.xaml中,您可以添加此样式,该样式将应用于UserControl1的所有实例
<Style TargetType="StyleTest:UserControl1" >
<Style.Resources>
<Style TargetType="Button">
<Setter Property="Background" Value="green" />
</Style>
</Style.Resources>
</Style>
答案 1 :(得分:2)
如果我理解正确,您只需要修改UserControl,以便在那里添加样式,而不是在Window控件中
<UserControl x:Name=UserControl1 ...>
<UserControl.Resources>
<Style TargetType="Button">
<Setter Property="Background" Value="green" />
</Style>
</UserControl.Resources>
我刚看到你说你不想修改控件。你的意思是你不能修改UserControl的xaml?为什么不呢?