Tom Xue
Tom Xue

Reputation: 3355

How to make a page template which can be initialized in Main Page C# code?

I want to make a page template in my UWP project, which can be initialized in main page in C# code.

For example, the page is like an introduction of painting work: a painting picture(could be an url representing the image), text introduction below. And I need to initialize these two elements in main page and dynamically create the new page in C# code. Because for each painting work, I need to use a new page for navigation and tracking.

How to do it? Thanks!

Upvotes: 1

Views: 187

Answers (1)

Anran Zhang
Anran Zhang

Reputation: 7727

I want to make a page template in my UWP project, which can be initialized in the main page in C# code.

For your requirement, you could create ImagePage that contains ImageModel class like the following. When the page navigated to the image and text label will be initialized with the parameter that comes from the main page.

Xaml

 <StackPanel>
     <Image Name="MyImage"/>
     <TextBlock Name="MyDescription"/>
 </StackPanel>

Code Behind

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

    public class ImageModel
    {
        public string ImageUrl { get; set; }
        public string Description { get; set; }
    }
    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        if (e.Parameter != null && e.Parameter is ImageModel)
        {
            var data = e.Parameter as ImageModel;
            MyImage.Source = new BitmapImage(new Uri(data.ImageUrl));
            MyDescription.Text = data.Description;
        }
    }

}

Then add Frame that use to navigate On the Main page.

<Grid>
  <Frame Name="ImageFrame"/>
</Grid>

Usage

public MainPage()
{
  this.InitializeComponent();
  var TestData=new ImageModel
  { 
    ImageUrl = "https://via.placeholder.com/150", 
    Description = "This is a test image"
  }

  ImageFrame.Navigate( typeof(ImagePage), TestData );
}

Now, when you start the application, your new image page will load in the frame.

This is a short example, the main purpose is to express how to jump to the page and give parameters to the page.

When the page receives a parameter, you can adjust the UI according to the parameter.

So, you can use the GridView to display all the images. When you click on one of them, use this principle to jump to the pre-designed page.

I hope this can help you.

Upvotes: 2

Related Questions