Reputation: 6744
If I have a UserControl
with the following two Label
s inside of it's grid like so:
<Grid x:Name="mainGrid">
<Label x:Name="labelTitle"/>
<Label x:Name="labelValue"/>
</Grid>
Can I set their styles separately from within a ResourceDictionary
something like:
<Style TargetType="{x:Type MyControl}">
<Style.Resources>
<Style TargetType="MyControl.mainGrid.labelTitle">
</Style>
<Style TargetType="MyControl.mainGrid.labelValue">
</Style>
</Style.Resources>
</Style>
If possible I would like to do all of this in the ResourceDictionary
and not have to touch the UserControl
at all.
Upvotes: 1
Views: 2414
Reputation: 4322
Try using a trigger in the style based on the name.
App.xaml
<Application x:Class="WpfApplication34.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication34"
StartupUri="MainWindow.xaml">
<Application.Resources>
<Style TargetType="{x:Type local:MyControl}">
<Style.Resources>
<Style TargetType="{x:Type Label}" BasedOn="{StaticResource {x:Type Label}}">
<Style.Triggers>
<Trigger Property="Name" Value="labelTitle">
<Setter Property="Content" Value="This is the Title" />
<Setter Property="HorizontalAlignment" Value="Left" />
</Trigger>
<Trigger Property="Name" Value="labelValue">
<Setter Property="Content" Value="This is the Value" />
<Setter Property="HorizontalAlignment" Value="Right" />
</Trigger>
</Style.Triggers>
</Style>
</Style.Resources>
</Style>
</Application.Resources>
</Application>
MyControl.xaml
<UserControl x:Class="WpfApplication34.MyControl"
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"
xmlns:local="clr-namespace:WpfApplication34"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid x:Name="mainGrid">
<Label x:Name="labelTitle" />
<Label x:Name="labelValue" />
</Grid>
</UserControl>
MainWindow.xaml
<Window x:Class="WpfApplication34.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication34"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<local:MyControl />
</Grid>
</Window>
Screenshot:
Upvotes: 5