wpf WPF中如何使用资源字典

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38916521/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 13:54:34  来源:igfitidea点击:

How to use resource dictionary in WPF

c#.netwpf

提问by Konrad

I'm new to WPF and I don't understand well how resource dictionary works. I have Icons.xaml that looks like:

我是 WPF 的新手,我不太了解资源字典的工作原理。我有 Icons.xaml 看起来像:

<ResourceDictionary xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas x:Key="appbar_3d_3ds" Width="76" Height="76" Clip="F1 M 0,0L 76,0L 76,76L 0,76L 0,0">
    <Path Width="32" Height="40" Canvas.Left="23" Canvas.Top="18" Stretch="Fill" Fill="{DynamicResource BlackBrush}" Data="F1 M 27,18L 23,26L 33,30L 24,38L 33,46L 23,50L 27,58L 45,58L 55,38L 45,18L 27,18 Z "/>
</Canvas>

<Canvas x:Key="appbar_3d_collada" Width="76" Height="76" Clip="F1 M 0,0L 76,0L 76,76L 0,76L 0,0">
    <Path Width="44" Height="30.3735" Canvas.Left="15" Canvas.Top="21.6194" Stretch="Fill" Fill="{DynamicResource BlackBrush}" Data="F1 M 39.2598,21.6194C 47.9001,21.6194 55.3802,24.406 59,28.4646L 59,33.4834C 56.3537,29.575 49.2267,26.7756 40.85,26.7756C 30.2185,26.7756 21.6,31.285 21.6,36.8475C 21.6,40.4514 25.2176,43.6131 30.6564,45.3929C 22.7477,43.5121 17.2,39.1167 17.2,33.9944C 17.2,27.1599 27.0765,21.6194 39.2598,21.6194 Z M 35.8402,51.9929C 27.1999,51.9929 19.7198,49.2063 16.1,45.1478L 15,40.129C 17.6463,44.0373 25.8733,46.8367 34.25,46.8367C 44.8815,46.8367 53.5,42.3274 53.5,36.7648C 53.5,33.161 49.8824,29.9992 44.4436,28.2194C 52.3523,30.1002 57.9,34.4956 57.9,39.6179C 57.9,46.4525 48.0235,51.9929 35.8402,51.9929 Z "/>
</Canvas>
</ResourceDictionary>

How can I use for example "app_3d_collada" in my xaml ? I have for example MenuItem and I would like to use this icon as my MenuItem icon.

我如何在我的 xaml 中使用例如“app_3d_collada”?例如,我有 MenuItem,我想将此图标用作我的 MenuItem 图标。

回答by Umair Farooq

First you have to specify the resource dictionary reference in App.xaml file.

首先,您必须在 App.xaml 文件中指定资源字典引用。

In App.xaml file, under Application.Resources tag

在 App.xaml 文件中,在 Application.Resources 标签下

<ResourceDictionary Source="Icons.xaml" />

The source of the resource dictionary can vary according the path where your resource dictionary is placed.

资源字典的来源可能因放置资源字典的路径而异。

Now in any of your Window or Page xaml file you can reference these styles/icons like the following

现在,在任何 Window 或 Page xaml 文件中,您都可以引用这些样式/图标,如下所示

<MenuItem Header="Reports" Icon="{StaticResource app_3d_collada}">
</MenuItem>

Same is the case for style. Hope that solves the problem.

风格也是如此。希望能解决问题。