Cannot bind Icon property in NavigationView MenuItemTemplate

点点圈 提交于 2019-11-30 16:27:08

This was driving me mad! Sadly, it seems the default behaviour is that the contents of MenuItemTemplate are placed inside the NavigationViewItem's ContentPresenter.

The way I got around this was to copy the relevant part of the default style for NavigationViewItem, and modify it slightly:

<NavigationView.MenuItemTemplate>
    <DataTemplate>
        <Grid HorizontalAlignment="Left"
              Height="40"
              Margin="-16,0,0,0">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="48" />
                <ColumnDefinition Width="*" />
            </Grid.ColumnDefinitions>
            <Viewbox Grid.Column="0"
                     Margin="16,12">
                <SymbolIcon Symbol="{x:Bind Icon}" />
            </Viewbox>
            <ContentPresenter Content="{x:Bind Name}"
                              Grid.Column="1"
                              VerticalAlignment="Center"/>
        </Grid>
    </DataTemplate>
</NavigationView.MenuItemTemplate>

The modification has included setting negative margin for the Grid and adding the two Grid.Column properties.

I've opened an issue on the Docs GitHub so hopefully they will explain the behaviour better.

You state that you dont want to manually add the icon as part of the MenuItemTemplate because it's not the way it's thought to be (which is absolutely correct), yet you actually do the exact same thing for setting the menu item's text (manually adding a TextBlock instead of setting the menu item's Content property).

The TextBlock overrides any NavigationItemView that is automatically created, so there is no icon element to be displayed (a TextBlock only contains text, no icon).

Try to simply use a NavigationViewItem as template:

<NavigationView MenuItemsSource="{Binding Items}">
    <NavigationView.MenuItemTemplate>
        <DataTemplate>
            <NavigationViewItem Icon="{Binding Icon}" Content="{Binding Name}"/>
        </DataTemplate>
    </NavigationView.MenuItemTemplate>
</NavigationView>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!