【发布时间】:2021-12-17 23:43:42
【问题描述】:
我有一个导航栏,里面有几个按钮。这些按钮都使用相同的样式,在 ResourceDictionary 中定义。
我正在尝试将 Mahapps 中的图标添加到每个按钮。每个按钮都需要不同类型的图标,我想在视图上设置它。
为了实现这一点,我需要能够通过按钮的某些属性将图标种类传递给模板。
我无法将图标种类传递给模板。
我正在一个新项目(WPF netcore3.1)上对此进行测试
我看到其他帖子(post1、post2)建议使用rectangle 而不是iconPacks,并使用按钮的Tag 属性绑定rectangle 的Visual 属性:
<Application x:Class="WpfApp1.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApp1"
StartupUri="MainWindow.xaml">
<Application.Resources>
<ResourceDictionary Source="/IconStyle.xaml" />
</Application.Resources>
<Window x:Class="WpfApp1.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:iconPacks="http://metro.mahapps.com/winfx/xaml/iconpacks"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<StackPanel>
<Button Style="{StaticResource IconStyle}" Foreground="Red">
<Button.Tag>
<iconPacks:Modern Kind="Home" Width="24" Height="24" />
</Button.Tag>
</Button>
</StackPanel>
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApp1">
<Style x:Key="IconStyle" TargetType="Button">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<StackPanel Orientation="Horizontal"
DataContext="{Binding RelativeSource={RelativeSource AncestorType=Button}}">
<Rectangle Width="24" Height="24" Fill="{Binding Foreground}">
<Rectangle.OpacityMask>
<VisualBrush Stretch="Fill" Visual="{Binding Tag}" />
</Rectangle.OpacityMask>
</Rectangle>
<TextBlock Margin="10 0 10 0" VerticalAlignment="Center" Text="John Doe"
FontSize="24" FontWeight="Normal" FontFamily="Segoe UI Light" />
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
但对我来说根本不显示任何图标。
有什么建议吗?
【问题讨论】:
-
我会尝试 Fill 而不是 Rectangle.OpacityMask
-
Rectangle.OpacityMask 在我对其中的图标进行硬编码时工作正常。仅当我尝试将 Kind 传递给模板时,该图标才显示
标签: c# wpf data-binding mahapps.metro