Setting styles for subcontrols of usercontrol
Say I have a user control like this:
<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>
And I want to set all buttons in this control to background=green. But I don't want to affect other buttons in my program and I don't want to modify the code of the control.
What I found right now is this:
<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="c开发者_JAVA百科lr-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>
But this would imply that I have to add this code to every instance of the control, and some extra code, if I want to style e.g. foreground color of TextBoxes also.
What I am looking for is something similar to this:
<Style TargetType="Buttons that are childs of UserControl1">
<Setter Property="Background" Value="green" />
</Style>
Is there a way of doing this?
I don't think that a control template would be sufficient, because I don't want to redesign the whole control, I just want to set the color of the buttons.
In App.xaml you could add this style which will be applied to all instances of UserControl1
<Style TargetType="StyleTest:UserControl1" >
<Style.Resources>
<Style TargetType="Button">
<Setter Property="Background" Value="green" />
</Style>
</Style.Resources>
</Style>
If I understand correctly, you just need to modify your UserControl so that you add the style there, instead of in the Window control
<UserControl x:Name=UserControl1 ...>
<UserControl.Resources>
<Style TargetType="Button">
<Setter Property="Background" Value="green" />
</Style>
</UserControl.Resources>
I just saw that you said you don't want to modify the control. You mean that you can't modify the xaml of the UserControl? Why not?
精彩评论