[英]Set style of a specific element of a UserControl by name
如果我的UserControl
的網格中包含以下兩個Label
,則如下所示:
<Grid x:Name="mainGrid">
<Label x:Name="labelTitle"/>
<Label x:Name="labelValue"/>
</Grid>
我可以在ResourceDictionary
單獨設置其樣式,例如:
<Style TargetType="{x:Type MyControl}">
<Style.Resources>
<Style TargetType="MyControl.mainGrid.labelTitle">
</Style>
<Style TargetType="MyControl.mainGrid.labelValue">
</Style>
</Style.Resources>
</Style>
如果可能的話,我想在ResourceDictionary
完成所有這些操作,而完全不必觸摸UserControl
。
嘗試使用基於名稱的樣式的觸發器。
應用程式
<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>
屏幕截圖:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.