【发布时间】:2021-05-27 12:44:52
【问题描述】:
我正在尝试在 WPF 中创建自定义按钮。
我有 Button 的基本 XAML,按钮内有两个 TextBlock 控件。一个是由 FontAwesome 渲染的图像,一个是文本。
<TextBlock Style="{DynamicResource mediumLabel}" Grid.Column="1" Grid.ColumnSpan="2" Grid.Row="4">SETTINGS</TextBlock>
<Button Grid.Column="1" Grid.Row="5" Grid.ColumnSpan="2" HorizontalAlignment="Stretch" Style="{DynamicResource mainButton}" Template="{DynamicResource mainButtonTemplate}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="40"/>
<ColumnDefinition Width="200"/>
</Grid.ColumnDefinitions>
<TextBlock x:Name="Image" Grid.Row="1" Grid.Column="0">cogs</TextBlock>
<TextBlock x:Name="Label" Grid.Row="1" Grid.Column="1" Text="SETTINGS" />
</Grid>
</Button>
我在App.xaml 中定义了全局样式。
我可以单独定位这三个元素中的每一个,在我的App.xaml 中使用单独的样式。
我想做什么,我想只是为了组织和便于将来使用,我想为Button 设置一个样式,并使用嵌套样式来定位两个TextBlock 控件中的每一个。每个都会有不同的样式,所以我不能定位 TextBlock 类型。我想按名称引用它们。
我尝试引用主要的control_name.childcontrol_name,以及控件名称。
我似乎无法在搜索时获得足够的信息来说明如何执行此操作,因为我可能正在搜索错误的术语...
我对嵌套样式的尝试,针对嵌套样式定位进行了两次尝试。
<Style x:Key="mainButton" TargetType="Button">
<Setter Property="Background" Value="White"/>
<Setter Property="Foreground" Value="DarkSlateGray"/>
<Setter Property="FontSize" Value="14"/>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Cursor" Value="Hand"/>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Foreground" Value="DodgerBlue"/>
</Trigger>
</Style.Triggers>
<Style.Resources>
<Style TargetType="{x:Reference Image}">
<Setter Property="FontFamily" Value="/Genesis_desktop;component/tools/fontawesome-free-5.15.1-desktop/otfs/#Font Awesome 5 Free Solid"/>
<Setter Property="FontSize" Value="14"/>
<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="HorizontalAlignment" Value="Center"/>
<Setter Property="ForeGround" Value="orange"/>
</Style>
<Style TargetType="{x:Reference mainButton.Label}">
<Setter Property="FontSize" Value="14"/>
<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="HorizontalAlignment" Value="Left"/>
</Style>
</Style.Resources>
</Style>
【问题讨论】: