WinUI3中如何通过x:Name或Tag定位NavigationViewItem并修改属性
问题场景
我在UWP项目中创建了NavigationView及多个NavigationViewItem,XAML代码如下:
<NavigationView x:Name="nvSample" SelectionChanged="nvSample_SelectionChanged" IsBackButtonVisible="Collapsed" IsSettingsVisible="False"> <NavigationView.MenuItems> <NavigationViewItem x:Name="NavigationViewItem_HomePage" Icon="Home" Content="Home" Tag="HomePage" IsSelected="True" /> <NavigationViewItem x:Name="NavigationViewItem_SimpleSortPage" Icon="Sort" Content="Sort" Tag="SimpleSortPage" /> <...........> </NavigationView.MenuItems> </NavigationView>
我希望通过x:Name或Tag获取对应的NavigationViewItem对象,从而修改它的Content和IsSelected属性。之前用Type.GetType可以获取页面类型(示例代码如下),于是尝试用同样方式获取NavigationViewItem,但方法无效:
// 可行的页面类型获取方式 Type pageSelected = Type.GetType("NumberSort.Pages.SimpleSort"); RootPageFrame.Navigate(pageSelected,this); // 无效的控件获取方式 var NavigationItem = (NavigationViewItem)Type.GetType("NavigationViewItem_HomePage");
解决方法
方法一:直接通过x:Name访问控件
在UWP中,XAML里设置了x:Name的控件会自动在后台代码生成对应字段,直接使用名称即可访问,不需要用Type.GetType:
// 修改Home页的Content和IsSelected属性 NavigationViewItem_HomePage.Content = "首页"; NavigationViewItem_HomePage.IsSelected = true;
方法二:通过Tag遍历查找控件
如果需要通过Tag动态查找,可遍历NavigationView的MenuItems集合匹配Tag值:
// 封装根据Tag查找NavigationViewItem的方法 NavigationViewItem FindNavItemByTag(string tag) { foreach (var item in nvSample.MenuItems) { if (item is NavigationViewItem navItem && navItem.Tag?.ToString() == tag) { return navItem; } } return null; } // 使用示例 var homeItem = FindNavItemByTag("HomePage"); if (homeItem != null) { homeItem.Content = "首页"; homeItem.IsSelected = true; }
失效原因说明
Type.GetType的作用是获取类型信息,比如示例中的NumberSort.Pages.SimpleSort是页面类的类型;而NavigationViewItem_HomePage是控件的实例名称,并非类型名称,因此用该方法无法获取到对应的控件对象。
内容的提问来源于stack exchange,提问作者Coco
相关产品推荐
相关产品推荐

