C#

Creating Navigation Window Application Using WPF in C#

In this post on Creating Navigation Window Application Using WPF in C#, I will show you how to create a navigation window application in WPF that consists of multiple pages. Basically, in such application we have several pages available which we can navigate using the navigation buttons. Also, we can pass the data values from one page to another.

Creating Navigation Window Application Using WPF in C#

An example of creating a navigation window in WPF is given below. Basically, the MainWindow is now a subclass of NavigationWindow class rather than being the subclass of Window class. Further, the application has two more pages displaying All Items and the Item Description.

What is a Navigation Window?

If your application requires the use of multiple pages then you should consider creating a Navigation Window Application. Basically, it is like other WPF applications with backward and forward buttons available for navigation. Further, the class that defines the navigation window application is a subclass of NavigationWindow which is in fact a subclass of Window class.

Example of Navigation Window Application

Let us look at this example given below. Here, the application has two pages – All Items and Item Description. The first page displays the name of certain items in a ListBox. When the user selects an item from the list and clicks on the Get Description button, the application displays the description of the selected item on the next page.

Create the Main Window

As evident from the following code, the Main Window is a subclass of Navigation Window and doesn’t contain the Grid tag. Also, set the source property to AllItems.xaml so that the content of this page display on the main window.

MainWindow.xaml

<NavigationWindow x:Class="WPFExample2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WPFExample2"
        mc:Ignorable="d"
        Title="All Items - Home" 
                 Height="550" Width="800"
                 Source="AllItems.xaml">
</NavigationWindow>

Add Another WPF Page – All Items

Now add a WPF page by selecting Add New Item from the Project menu in Visual Studio. Further, add rows and columns as specified earlier and finally add the three controls – Label, ListBox, and Button. Also, add the event handler function for the Button.

AllItems.xaml

<Page x:Class="WPFExample2.AllItems"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      xmlns:local="clr-namespace:WPFExample2"
      mc:Ignorable="d" 
      d:DesignHeight="350" d:DesignWidth="800"
      Title="All Items">
    <Grid Margin="10,10,10,10">
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <Label Grid.Row="0" Grid.Column="0"
               FontFamily="Comic Sans MS" FontSize="30"
               FontWeight="Black" HorizontalContentAlignment="Center"
               Foreground="DarkOrange"
               Background="DarkRed"
               Padding="10,10,10,10">
            Select an Item:
        </Label>
        <ListBox x:Name="mylist" Grid.Row="1" 
                 Grid.Column="0"
                 FontFamily="Comic Sans MS" FontSize="30"
               FontWeight="Black"
               Foreground="DarkOrange"
               Background="DarkRed"
               Padding="10,10,10,10">

        </ListBox>
        <Button Grid.Row="2" Grid.Column="0" 
               FontFamily="Comic Sans MS" FontSize="30"
               FontWeight="Black" HorizontalContentAlignment="Center"
               Foreground="DarkOrange"
               Background="DarkRed"
               Padding="10,10,10,10"
                Click="Button_Click">
            Get Description
        </Button>
    </Grid>
</Page>

Add One More WPF Page

Now, add another WPF page – Item Description that contains one column and two rows. Also, set the background image of this page. The two rows on the page contain a Label and a TextBlock respectively.

ItemDescription.xaml

<Page x:Class="WPFExample2.ItemDescription"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      xmlns:local="clr-namespace:WPFExample2"
      mc:Ignorable="d" 
      d:DesignHeight="350" d:DesignWidth="500"
      Title="Item Description">
    <Grid Margin="10,10,10,10">
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <Label Grid.Row="0" Grid.Column="0"
               Height="40" Width="350"
               FontSize="25" FontWeight="ExtraBlack"
               FontFamily="Forte" HorizontalAlignment="Center"
               HorizontalContentAlignment="Center"
               Foreground="DarkMagenta"
               Background="LightPink">
            Item Description
        </Label>
        <TextBlock Grid.Row="1" Grid.Column="0"
                   Width="350" TextWrapping="Wrap"
                   Height="Auto" Background="LightPink"
                   Foreground="DarkMagenta"
                   x:Name="t1"
                   Margin="5,5,5,5"
                   FontSize="20" FontWeight="Bold"
                   FontFamily="Forte"
                   LineHeight="2" Padding="10,10,10,10">
            
        </TextBlock>
        <Grid.Background>
            <ImageBrush ImageSource="g2.jpg"/>
        </Grid.Background>          
    </Grid>
</Page>

Now, open the .cs files for all the pages and implement the desired functionality. First, define a partial class called MyItems in the MainWindow.xaml.cs file. Further, create an array of objects of MyItems class in AllItems.xaml.cs to initialze the ListBox with Item names.

MainWindow.xaml.cs

using System;
using System.Windows.Navigation;

namespace WPFExample2
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MyItems
    {
        public String ItemName, Category, Seller;
        public double price;

        public String ShowDescription()
        {
            String str = "";
            str += "Item Name: " + ItemName;
            str += "\nCategory: " + Category;
            str += "\nSeller: " + Seller;
            str += "\nItem Price: " + price;
            return str;
        }
    }
    public partial class MainWindow : NavigationWindow
    {
        public MainWindow()
        {
            InitializeComponent();
            
            
        }
    }
}

Now, open the AllItems.xaml.cs file and create an array of MyItems objects and add Item Names to the ListBox. Next, implement the event handler of the Button. In this event handler function, retrieve the name of the selected item, create the object of ItemDescription, and navigate to that page.

AllItems.xaml.cs

using System;
using System.Windows;
using System.Windows.Controls;


namespace WPFExample2
{
    /// <summary>
    /// Interaction logic for AllItems.xaml
    /// </summary>
    
    public partial class AllItems : Page
    {
        public static MyItems[] arr = new MyItems[]
               {
                new MyItems{ItemName="Car Phone Holder", Category="Mobile Accessories", Seller="MRN", price=339.0},
                new MyItems{ItemName="Snake Plant", Category="Indoor Plants", Seller="ABC", price=228.5},
                new MyItems{ItemName="Bamboo Plant", Category="Indoor Plants", Seller="ABC", price=590.0},
                new MyItems{ItemName="Camera Lens Protector", Category="Mobile Accessories", Seller="XYZ", price=430.0},
                new MyItems{ItemName="Smart Band", Category="Fitness", Seller="XYZ", price=400.0},
                new MyItems{ItemName="Headphone", Category="Electronics", Seller="XYZ", price=899.0},
                new MyItems{ItemName="Fitness Watch", Category="Fitness", Seller="ABC", price=2800.0}
               };
        public AllItems()
        {
            InitializeComponent();
            

            foreach (MyItems ob in arr)
                mylist.Items.Add(ob.ItemName);
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            String str="";
            if(mylist.SelectedItem!=null)
                str = mylist.SelectedItem.ToString();
            if (String.IsNullOrEmpty(str))
                str = "No Item Selected!";
            ItemDescription ob = new ItemDescription(str);
            this.NavigationService.Navigate(ob);
        }
    }
}

Finally, open the file ItemDescription .xaml.cs, create a constructor that accepts a string and calls the ShowDescription method.

ItemDescription.xaml.cs

using System;
using System.Windows.Controls;

namespace WPFExample2
{
    /// <summary>
    /// Interaction logic for ItemDescription.xaml
    /// </summary>
    public partial class ItemDescription : Page
    {
        public ItemDescription()
        {
            InitializeComponent();
            
        }
        public ItemDescription(String str):this()
        {
            String str1 = str;
            foreach(MyItems ob in AllItems.arr)
            {
                if(ob.ItemName.Equals(str))
                {
                    str1 = ob.ShowDescription();
                }
            }
            t1.Text = str1;
            
        }
    }
}

Output of the application is displayed as shown below.

Output

Creating Navigation Window Application Using WPF in C#
The Home page in Main Window
Navigation Window in WPF
Navigating to Another Page

Summary

In this article on Creating Navigation Window Application Using WPF in C#, I have shown how to create a navigation window application consisting of two pages and how to transfer data from one page to another page.


Related Topics

A Beginner’s Tutorial on WPF in C#

Everything about Tuples in C# and When to Use?

Linear Search and Binary Search in C#

Creating Jagged Arrays in C#

Learning Indexers in C#

Understanding Method Parameter Modifiers in C#

Object Initializers in C#

Examples of Static Constructors in C#

When should We Use Private Constructors?

C# Practice Questions

C# Basic Examples

Private and Static Constructors in C#

Constructors in C#

C# Arrays

C# Examples

How to Create a C# Console Application

Leave a Reply

Your email address will not be published. Required fields are marked *