wpf - 从资源中使用图标时,仅显示 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>
结果是一个如下所示的窗口:
在 xaml 编辑器中,所有按钮上都有图标,正如预期的那样:
为什么会发生这种情况,更重要的是,如何解决这个问题?
PS 我们发现,如果您Cash
在 中创建两个图标ResourceDictionary
并将每个图标应用于一个按钮,那么它们都会显示,但同样,只有一次,您不能在 中说 3 个按钮和 2 个图标ResourceDictionary
。
解决方案
类型PackIcon
是. Control
WPF 中的可视化树中的元素只能有一个父元素。换句话说,包图标仍然是作为第一个按钮的子元素添加的单个实例,然后移至第二个,然后移至第三个。实际上,您必须创建包图标的多个实例。
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>
推荐阅读
- c# - JsonConvert.DeserializeObject System.NullReferenceException
- php - 作曲家如何知道使用了哪些类?
- c++ - 查找向量c ++中是否已存在结构
- html - 在 HTML Angular 中显示/隐藏 Angular 中的列表项
- text - 修复没有空格的英文文本
- javascript - 在我的 Mocha 测试报告中抛出 Silent Sinon 存根错误
- reactjs - 如何在构象提示中使用 NavLink
- scala - Scala 广播 + UDF
- javascript - 如何更改javascript中的背景文本
- angular - 在Angular 9中显示基于默认地址路由的组件