从后面的代码设置 UWP NavigationViewItem 图标

Set UWP NavigationViewItem Icon from code behind

我希望能够在我的 UWP 应用程序中动态添加 NavigationViewItems,但我不知道如何设置图标。

XAML 中的

NavigationViewItem.Icon 格式为:Icon="Page",看起来它正在使用 Symbol 枚举。除了 C# 说它是一个 IconElement 对象

我希望能够写出这样的东西:

NavigationViewItem navItem = new NavigationViewItem();
navItem.Icon = Symbol.Page;
navView.MenuItems.Add(navItem)

编译器在 Symbol.Page 处报错,因为它不是 IconElement,有什么方法可以将它转换为 IconElement?

本例中的 XAML 语法创建 IconElement for you automatically when the XAML is compiled. When you do it from code you need to create it manually. There is a SymbolIcon class that inherits from IconElement that does the same in code. Check also the documentation for IconElement derived classes 以查看所有可能的图标类型。

固定码也在这里:

NavigationViewItem navItem = new NavigationViewItem();
navItem.Icon = new SymbolIcon(Symbol.Page);
navView.MenuItems.Add(navItem);