简体   繁体   中英

uwp create xaml or new page dynamically

I am new to uwp, I don't want to create multiple static xaml file, how to create new page, add dynamic controls to that page and navigate

namespace UItest
{
   // <summary>
   // An empty page that can be used on its own or navigated to within a 
   // </summary>
   public sealed partial class MainPage : Page
   {
     public MainPage()
     {
        InitializeComponent();
     }
     private void btntest_Click(object sender, RoutedEventArgs e)
     { 
       Frame.Navigate(typeof(page2));
     }
   }

   public sealed partial class page2 : Page
   {
     public page2()
     {
        Button bt = new Button();
         bt.Content = "page2";
      } 
   }
}

In above code I am trying to create new class(page2), in button click event it should navigate to page

Not sure if that is possible, maybe is, as most of XAML things can be also done in the code behind. Nevertheless, maybe try something different - create one basic template of a page - let's call it MultiPage , and redesign it on OnNavigatedTo basing on suitable passed argument. A short sample - MultiPage's code behind:

public enum PageType { First, Second }

public sealed partial class MultiPage : Page
{
    public MultiPage()
    {
        this.InitializeComponent();
    }

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        base.OnNavigatedTo(e);
        switch ((PageType)e.Parameter)
        {
            case PageType.First:
                this.Content = new Button { Content = "First page" };
                break;
            case PageType.Second:
                this.Content = new Button { Content = "Second page" };
                break;
            default:
                break;
        }
    }
}

and way of navigation to that page:

private void FirstClick(object sender, RoutedEventArgs e)
{
    this.Frame.Navigate(typeof(MultiPage), PageType.First);
}

private void SecondClick(object sender, RoutedEventArgs e)
{
    this.Frame.Navigate(typeof(MultiPage), PageType.Second);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM