You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于字符串值使用UWP的Frame.Navigate()方法

UWP Navigation Without Switch Statements: Dynamic Page Loading

Hey there! Let's tackle this UWP navigation problem you're having—ditching the switch statement for a more scalable approach is totally a great goal, especially as you add more pages later. I'll walk you through why your previous attempts didn't work, and give you two solid solutions to make this work smoothly.

Why Your Previous Tries Failed

Let's break down the issues with the code you tried:

  • FindName(pageName): This method looks for UI elements in the current XAML tree, not C# class types. So it can't find your page class, hence the null reference.
  • Type.GetType(this.GetType().Namespace + "." + pageName): This can fail in UWP because Type.GetType often needs the full assembly name to locate the type correctly, especially if your pages are in a different assembly or the namespace structure is more complex.
  • typeof(pageObj) or typeof(pageName): The typeof operator only works with compile-time known types, not variables or strings. So these calls were never going to work as intended.

Solution 1: Reliable Type Lookup with Assembly Information

If you want to stick with using the ListViewItem.Name to match page class names, you need to pass the full assembly qualified name to Type.GetType. Here's how to adjust your code:

private void ListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (e.AddedItems.Count == 0) return;

    var selectedItem = e.AddedItems[0] as ListViewItem;
    if (selectedItem == null) return;

    var pageClassName = selectedItem.Name;
    var fullTypeName = $"{this.GetType().Namespace}.{pageClassName}, {this.GetType().Assembly.GetName().Name}";
    var pageType = Type.GetType(fullTypeName);

    if (pageType != null)
    {
        MyFrame.Navigate(pageType);
    }
    else
    {
        // Handle the case where the type wasn't found (e.g., log an error or show a message)
        // This helps catch typos between ListViewItem.Name and your page class name
    }
}

This works because we're explicitly telling Type.GetType which assembly to look in (your app's main assembly), which fixes the null reference issue you were seeing. Just make sure your ListViewItem.Name exactly matches the class name of your page (e.g., if your page is MyNamespace.HomePage, the ListViewItem's Name should be HomePage).

Solution 2: Use Tag to Bind Page Types (More Robust & Elegant)

A cleaner, safer approach is to store the page type directly in the ListViewItem.Tag property in XAML. This avoids string matching entirely, and gives you compile-time checks if you ever rename a page class.

First, update your XAML to add the Tag property with the page type:

<!-- Make sure you have your namespace declared at the top of the XAML file, e.g.:
xmlns:local="using:MyNamespace"
-->
<ListView SelectionChanged="ListView_SelectionChanged">
    <ListViewItem Name="HomePage" Tag="{x:Type local:HomePage}">
        <TextBlock Text="Home" />
    </ListViewItem>
    <ListViewItem Name="SettingsPage" Tag="{x:Type local:SettingsPage}">
        <TextBlock Text="Settings" />
    </ListViewItem>
    <!-- Add new ListViewItems here with their corresponding Tag -->
</ListView>

Then update your code-behind to read the Tag directly:

private void ListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (e.AddedItems.Count == 0) return;

    var selectedItem = e.AddedItems[0] as ListViewItem;
    if (selectedItem?.Tag is Type pageType)
    {
        MyFrame.Navigate(pageType);
    }
}

This is my recommended approach because:

  • No more string typos causing null references
  • If you rename a page class, Visual Studio will throw a compile error in the XAML, so you catch issues early
  • It's more readable and maintainable as your app grows

Either of these methods will let you add new pages just by adding a new ListViewItem—no need to modify any switch statements or navigation logic. Welcome to UWP and C#—great job thinking about scalable, elegant code early on!

内容的提问来源于stack exchange,提问作者master_ruko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:35:58