首页 > 解决方案 > 从资源中使用图标时,仅显示 XAML 中的最后一个图标

问题描述

当我尝试使用 中定义的图标包中的材料设计图标时ResourceDictionary,仅在运行时呈现 XAML 中的第一个图标。我遵循了一个可以在此处找到的示例。

示例如下:

应用程序.xaml:

<Application x:Class="TestWpf.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:TestWpf"
             xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <materialDesign:BundledTheme BaseTheme="Light" PrimaryColor="DeepPurple" SecondaryColor="Lime" />
                <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Defaults.xaml" />
                <ResourceDictionary Source="pack://application:,,,/TestWpf;component/Dictionary1.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

字典1.xaml:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes">
    <materialDesign:PackIcon x:Key="CashIcon" Kind="Cash" />
</ResourceDictionary>

MainWindow.xaml:

<Window x:Class="TestWpf.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="450" Width="800">
    <StackPanel>
        <Button Content="{DynamicResource CashIcon}" />
        <Button Content="{DynamicResource CashIcon}" />
        <Button Content="{DynamicResource CashIcon}" />
    </StackPanel>
</Window>

结果是一个如下所示的窗口:

窗口有 3 个按钮,前两个是空的,第三个有一个现金图标。

在 xaml 编辑器中,所有按钮上都有图标,正如预期的那样:

带有 3 个按钮的窗口,上面都有现金图标

为什么会发生这种情况,更重要的是,如何解决这个问题?

PS 我们发现,如果您Cash在 中创建两个图标ResourceDictionary并将每个图标应用于一个按钮,那么它们都会显示,但同样,只有一次,您不能在 中说 3 个按钮和 2 个图标ResourceDictionary

标签: wpfxamlmaterial-design

解决方案


类型PackIcon是. ControlWPF 中的可视化树中的元素只能有一个父元素。换句话说,包图标仍然是作为第一个按钮的子元素添加的单个实例,然后移至第二个,然后移至第三个。实际上,您必须创建包图标的多个实例。

PackIcon您可以使用标记扩展而不是创建资源。

<StackPanel>
   <Button Content="{materialDesign:PackIcon Cash}"/>
   <Button Content="{materialDesign:PackIcon Cash}"/>
   <Button Content="{materialDesign:PackIcon Cash}"/>
</StackPanel>

根据您的实际情况,您也可以创建一个DataTemplate,它将自动为每个按钮创建包图标的实例。

<DataTemplate x:Key="CashPackIconTemplate">
   <materialDesign:PackIcon Kind="Cash" />
</DataTemplate>
<StackPanel>
   <Button ContentTemplate="{StaticResource CashPackIconTemplate}"/>
   <Button ContentTemplate="{StaticResource CashPackIconTemplate}"/>
   <Button ContentTemplate="{StaticResource CashPackIconTemplate}"/>
</StackPanel>

推荐阅读