Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set UWP NavigationViewItem Icon from code behind

I want to be able to dynamically add NavigationViewItems in my UWP app, but I can't figure out how to set the icons.

NavigationViewItem.Icon in XAML is formatted: Icon="Page", which looks like it's using the Symbol enum. Except C# says that it's an IconElement object

I want to be able to write something like this:

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

The compiler spits an error at Symbol.Page because it's not an IconElement, is there any way I can convert it to an IconElement?

like image 600
Ben Avatar asked Jan 26 '19 20:01

Ben


1 Answers

The XAML syntax in this case creates the 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 to see all the possible icon types.

Here is also the fixed code:

NavigationViewItem navItem = new NavigationViewItem();
navItem.Icon = new SymbolIcon(Symbol.Page);
navView.MenuItems.Add(navItem);
like image 142
AlesD Avatar answered Nov 01 '22 17:11

AlesD