top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Adding a Page Load event in XAML ( Window Store Apps )?

+2 votes
809 views

We've worked a lot on windows forms applications in C#.NET.

Page load event automatically added into the form.cs file when you double click anywhere on your form in windows form application. But this is not the case in UWP Applications. UWP stands for Universal Windows platform. XAML apps does't provide you the event handler for the page when you double clicks anywhere on your page in XAML apps.

So in order to add a page load event in XAML Apps. Make a UWP Project from Visual Studio. To make a project , open visual studio and select new project as given below,

  • Select "Universal" from left side.
     
  • Choose "Blank App ( Universal Windows )". and press enter.

Open MainPage.xaml from Solution explorer. Main page with visual design will be displayed.

type an event in opening tag of "Page" named " Loaded " just like below screenshot. An event handler for the page loading will be added to .cs file behind the UI page.

Take your cursor on the name of event which is "Page_Loaded" here and press F12 , you'll be redirected to the event handler in code page.

See the screen shot of event below.

posted Mar 18, 2016 by Jdk

  Promote This Article
Facebook Share Button Twitter Share Button LinkedIn Share Button


Related Articles

 

Introduction

The purpose of this sample is to show how to bind a Dictionary a Lisbox in apps based in XAML, using the MVVM pattern.

Building the Sample

You only need Visual Studio 2012/2013 running in Windows 7, 8, 8.1 or later.

Description

Suppose we have a resource dictionary with some data that we need to show in an application and for each item in a Listbox, we want to show the key/value.

We will start by creating a model class called "Company" that has only two properties: Name and URL.
C#
/// <summary>   
/// Define the Company.   
/// </summary>   
public class Company   
{   
    /// <summary>   
    /// Gets or sets the name.   
    /// </summary>   
    /// <value>The name.</value>   
    public string Name { get; set; }   
  
    /// <summary>   
    /// Gets or sets the URL.   
    /// </summary>   
    /// <value>The URL.</value>   
    public string Url { get; set; }   

In the MainViewModel we will create the resource dictionary where the Company is the key and the value will be an int and we will have a SelectedCompany property to get the company selected in the listbox.

The MainViewModel will be defined by:

C#

public class MainViewModel : ViewModelBase   
{   
   private Company _selectedCompany;   
  
   /// <summary>   
   /// Initializes a new instance of the MainViewModel class.   
   /// </summary>   
   public MainViewModel()   
   {   
      Companies = new Dictionary<Company, int>   
      {   
         {   
            new Company   
            {   
               Name = "Microsoft", Url="www.microsoft.com"   
            }, 1   
         },   
         {   
            new Company   
            {   
               Name = "Google", Url="www.google.com"   
            }, 2   
         },   
         {   
            new Company   
            {   
               Name = "Apple", Url="www.apple.com"   
            }, 3   
         }   
      };   
   }   
  
   /// <summary>   
   /// Gets or sets the selected company.   
   /// </summary>   
   /// <value>The selected company.</value>   
   public Company SelectedCompany   
   {   
      get { return _selectedCompany; }   
      set { Set(() => SelectedCompany, ref _selectedCompany, value); }   
   }   
  
   /// <summary>   
   /// Gets or sets the companies.   
   /// </summary>   
   /// <value>The companies.</value>   
   public Dictionary<Company, int> Companies { get; set; }   
}  

The MainWindow will defined as in the following:


XAML

 

<mui:ModernWindow x:Class="BindingResourceDictionarySample.MainWindow"   
                  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"   
                  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"   
                  xmlns:mui="http://firstfloorsoftware.com/ModernUI"   
                  Title="Sample"   
                  Width="525"   
                  Height="350"   
                  DataContext="{Binding Main,   
                                        Source={StaticResource Locator}}"   
                  Style="{StaticResource BlankWindow}">   
    <StackPanel>   
        <TextBlock Margin="20,20,0,0" Text="How to binding a Dictionary to a Listbox" />   
        <ListBox Width="250"   
                 Margin="20,20,0,0"   
                 HorizontalAlignment="Left"   
                 ItemsSource="{Binding Companies}"   
                 SelectedValue="{Binding ItemIndex}"   
                 SelectedValuePath="Key"   
                 SelectionMode="Single">   
            <ListBox.ItemTemplate>   
                <DataTemplate>   
                    <Border Width="245"   
                            BorderBrush="Orange"   
                            BorderThickness="2">   
                        <StackPanel Orientation="Horizontal">   
                            <TextBlock Margin="20,0,0,0" Text="{Binding Path=Value}" />   
                            <TextBlock Margin="20,0,0,0" Text="{Binding Path=Key.Name}" />   
                        </StackPanel>   
                    </Border>   
                </DataTemplate>   
            </ListBox.ItemTemplate>   
        </ListBox>   
    </StackPanel>   
</mui:ModernWindow>

To get the selected Company the SelectedValue property from the Listbox will be used that will use the SelectedValuePath to understand which value to return. To get the value instead of the Company we should change the Key to Value.

Note:   

  1. To have a nice look, we will use the ModernWindow from the ModernUI (for WPF). For more see the ModerUI in Modern UI Samples.
     
  2. The sample is similar to any XAML app, where we show the UI for WPF.

Running the sample
 

binding a dictonary


Source code files:

 

  • ViewModelLocator class contains static references to all the view model in the application and provide an entry point for the bindings.
     
  • MainViewModel class for binding to MainView.xaml
     
  • MainWindow represents the view.
     
  • Company defines the model.
READ MORE

XAML is mostly used at design-time but there may be a time when you want to create XAML dynamically and/or load XAML in your code. The XamlWriter and the XamlReader classes are used to create and read XAML in code.

The XamlWriter and the XamlReader classes are defined in the System.Windows.Markup namespace and must be imported to use the classes as in the following:

using System.Windows.Markup;

The XamlWriter.Save method takes an object as an input and creates a string containing the valid XAML.

The code snippet in Listing 1 creates a Button control using code and saves it in a string using the XamlWriter.Save method.

 

// Create a Dynamic Button.

Button helloButton = new Button();

helloButton.Height = 50;

helloButton.Width = 100;

helloButton.Background = Brushes.AliceBlue;

helloButton.Content = "Click Me";

 

// Save the Button to a string.

string dynamicXAML = XamlWriter.Save(helloButton);

 

Listing 1

The XamlReader.Load method reads the XAML input in the specified Stream and returns an object that is the root of the corresponding object tree.

The code snippet in Listing 2 creates a XmlReader from a XAML and then creates a Button control using the XamlReader.Load method.

 

// Load the button

XmlReader xmlReader = XmlReader.Create(new StringReader(dynamicXAML));

Button readerLoadButton = (Button)XamlReader.Load(xmlReader);   

Listing 2

READ MORE

Data passing means to get data from a page and show that data on another page or getting input from the user and showing what the user has entered into the text box. For that I have added the two pages MainPage.xaml and page1.xaml and I will enter some text into the text box and on clicking Enter or the the submit button it will show the entered text in the second page.

This Is The MainPage.Xaml

  1. <StackPanel>    
            <TextBox InputScope="Chat" Name="TextBoxUsername"></TextBox>    
            <Button Click="Button_Click">Signup</Button>    
    </StackPanel> 

In the mainpage.xaml I have put a stack panel and in the stack panel I have used two controls, a TextBox control and a Button control. Here when I enter any text into the text box and click the button it will navigate to page1.xaml and show the entered text in the Page1.xaml as a message dialog. 

MainPage.xaml.cs

     

       private void Button_Click(object sender, RoutedEventArgs e)    
        {    
           NavigationService.Navigate(new Uri("/Page1.xaml?key1=" + TextBoxUsername.Text, UriKind.Relative));    
       }   

Defined a click event in the Mainpage.xaml.cs and using NavigationService.navigate property navigating to Page1.xaml using a query string.

Page1.xaml

​     <StackPanel Grid.Row="0" Margin="12,17,0,28">    
            <TextBlock Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}"/>    
            <TextBlock Name="TextBlockUsername" Text="" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>    
</StackPanel>  

In Page1.xaml I have use some controls to show the incoming data.

Page1.xaml.cs

In Page1.xaml.cs under the initialize component Page1_loaded method was called and in the Page1_loaded method definition a string variable val was declared to return the incoming data in the string variable val and showing that data in a message dialog box.

     

public partial class Page1 : PhoneApplicationPage      
 {      
     public Page1()      
     {      
         InitializeComponent();      
         this.Loaded += Page1_Loaded;      
      }      
      
     private void Page1_Loaded(object sender, RoutedEventArgs e)      
     {      
         string val;      
         if (NavigationContext.QueryString.TryGetValue("key1", out val))      
         {      
             MessageBox.Show(val, "Information", MessageBoxButton.OK);      
         }      
     }      
 }    

 

 

 

READ MORE

In this article you will learn how to create and use a CustomResource in XAML.

 

  1. Open a new Visual C# windows project.
     
  2. Add a new class named say CustomResourceTest.cs in the project folder.

    CustomResourceTest.cs
     
  3. Derive this class from CustomXamlResourceLoader Class(Case sensitive) like below:

    CustomXamlResourceLoader Class
     
  4. You will get a Namespace not found error. Resolve it by using Windows.UI.Xaml.Resources Namespace.

    Windows.UI.Xaml.Resources
     
  5. Override the GetResource Member of the parent class as below. Use the intellisense to select the member.

    getresource

    getresource1
     
  6. Replace the Code inside the GetResource Method as: (this is just a simple example). We are returning a text. We plan to show this text inside a TextBlock’s Text Property.

    TextBlock
     
  7. Inside the MainPage.cs . Add the following line of code inside the MainPage Constructor to reference the CustomResouceTest.cs Class from the Page’s XAML.

    MainPage

    Correct the NameSpace not found error by resolving it.
     
  8. Now go to the MainPage.xaml Page and Add a TextBlock as follows. Notice the Text property of the TextBlock.

    MainPage.xaml
     
  9. This results in the following output when you save, build and run the project.

    run
     
  10. What is happening here?
     
    • We created a CustomResourceClass where we inherited the Class called CustomXamlResourceLoader.
    • We override the GetResourceProperty. Don’t focus on the parameters of this method for now.
    • We replaced the code inside this method by simply returning a text.
    • To access this CustomResource from XAML we have to define the CustomXamlResourceLoader. Current property to the new instance of the Class we created. We have to do this inside the Constructor of the Codebehind page where we want to use the CustomResource.
    • We then simply assigned the value of the Text property of the textblock to the CustomResource as seen on Step 8.

Example 2:

  1. Now we will try a different example where we want to display the Text of the TextBlock based on the value we pass on. Change the text of the Mainpage.xaml as:

    Mainpage.xaml 2
     
  2. The 'sayHello' string is passed as a string to the CusomResourceTest.cs class as ResourceID parameter of the overridden class. This will be more clear as you see in the next step.
     
  3. In the CustomResourceTest.cs class , change the code as follows:

    CustomResourceTest.cs2
     
  4. The thing to understand is how we pass the ResourceID from the Text Property of the TextBlock. It is passed as the resourceID parameter. So, based on the ResourceID, we return the appropriate text we want to display on the output screen.
     
  5. So now we get output as.
  6. If we change the text property as sayByeBye.

    sayByeBye
     
  7. We get the following output:
     
READ MORE

Introduction 

The RichTextBox control allows you to view and edit text, paragraph, images, tables and other rich text format contents. 

The RichTextBox tag represents a RichTextBox control in XAML. 

<RichTextBox></RichTextBox>  

The Width and Height properties represent the width and the height of a RichTextBox. The Name property represents the name of the control, that is a unique identifier of a control. The Margin property tells the location of a RichTextBox on the parent control. The HorizontalAlignment andVerticalAlignment properties are used to set horizontal and vertical alignments. 

The following code snippet sets the name, height and width of a RichTextBox control. The code also sets the horizontal alignment to left and the vertical alignment to top. 

<RichTextBox Margin="10,10,0,13" Name="RichTextBox1" HorizontalAlignment="Left"   

                 VerticalAlignment="Top" Width="500" Height="300" />  

Displaying and Edit Text 

RichTextBox control hosts a collection of RichTextBoxItem. The following code snippet adds items to a RichTextBox control.

   

<RichTextBox Margin="10,10,0,13" Name="RichTextBox1" HorizontalAlignment="Left"   
             VerticalAlignment="Top" Width="500" Height="300">  
    <FlowDocument>  
        <Paragraph>  
            I am a flow document. Would you like to edit me?  
            <Bold>Go ahead.</Bold>                  
        </Paragraph>  
        
        <Paragraph Foreground="Blue">            
            I am blue I am blue I am blue.    
        </Paragraph>  
    </FlowDocument>          
</RichTextBox> 

The preceding code generates Figure 1 where you can begin editing text right away.

RichTextBox with editable text

Creating and Using RichTectBox Dynamically 

In the previous section, we saw how to create and use a RichTextBox in XAML. WPF provides the RichTextBox class that represents a RichTextBox control. In this section, we will see how to use this class to create and use a RichTextBox control dynamically. 

The code listed in Listing 1 creates a FlowDocument, adds a paragraph to the flow document and sets the Document property of the RichTextBox to FlowDocument.

       


private void CreateAndLoadRichTextBox()  
{  
    // Create a FlowDocument  
    FlowDocument mcFlowDoc = new FlowDocument();  
  
    // Create a paragraph with text  
    Paragraph para = new Paragraph();  
    para.Inlines.Add(new Run("I am a flow document. Would you like to edit me? "));  
    para.Inlines.Add(new Bold(new Run("Go ahead.")));  
  
    // Add the paragraph to blocks of paragraph  
    mcFlowDoc.Blocks.Add(para);  
  
    // Create RichTextBox, set its hegith and width  
    RichTextBox mcRTB = new RichTextBox();  
    mcRTB.Width = 560;  
    mcRTB.Height = 280;  
  
    // Set contents  
    mcRTB.Document = mcFlowDoc;  
  
    // Add RichTextbox to the container  
    ContainerPanel.Children.Add(mcRTB);       
}  

Listing 1

The output of Listing 1 generates Figure 2.

Listing 1 doc

Enable Spelling Check 

RichTextBox control comes with spell check functionality out-of-the-box. By setting theSpellCheck.IsEnabled property to true enables spell checking in a RichTextBox

SpellCheck.IsEnabled="True"  

You can set this in code as follows:

mcRTB.SpellCheck.IsEnabled = true;  

Now if you type some text, the wrong word would be underlined with the Red color. See in Figure 3.

RichTextBox with Spell Check Enabled


Loading a Document in RichTextBox
We can use the RichTextBox.Items.Remove or RichTextBox.Items.RemoveAt methods to delete an item from the collection of items in the RichTextBox. The RemoveAt method takes the index of the item in the collection. 
Now, we modify our application and add a new button called Delete Item. The XAML code for this button looks as in the following:  

private void LoadTextDocument(string fileName)  
{  
    TextRange range;  
    System.IO.FileStream fStream;  
    if (System.IO.File.Exists(fileName))  
    {  
        range = new TextRange(RichTextBox1.Document.ContentStart, RichTextBox1.Document.ContentEnd);  
        fStream = new System.IO.FileStream(fileName, System.IO.FileMode.OpenOrCreate);  
        range.Load(fStream, System.Windows.DataFormats.Text );  
        fStream.Close();  
    }  
}

READ MORE

The XAML Tooltip element represents a window tooltip. A ToolTip is a pop-up window that displays some information in a small window. This article shows how to use a ToolTip control in WPF.

Creating a ToolTip

The ToolTip element represents a ToolTip control in XAML

<ToolTip/>  

The IsOpen property indicates whether or not a ToolTip is visible. The HorizontalOffset and VerticalOffsetproperties represent the horizontal and vertical distance between the target control and the pop-up window. The Content property represents the contents of the ToolTip. 

The code snippet in Listing 1 creates a ToolTip control and sets the horizontal offset, vertical offset and content of a ToolTip control. 

   

<ToolTip Content="Hello! I am a ToolTip."   
HorizontalOffset="10" VerticalOffset="20"/> 

                                                            Listing 1

The output looks as in Figure 1. 

                                              Creating a ToolTip
                                       

ToolTip Service

To display a tooltip for a control, the ToolTipService class must be used. The SetToolTip and GetToolTipstatic methods are used to set and get the tooltip of a control. 

The following code snippet creates a ToolTipService.ToolTip for a control.

    

<ToolTipService.ToolTip >   
    <ToolTip Content="Hello! I am a ToolTip."   
    HorizontalOffset="10" VerticalOffset="20"/>  
</ToolTipService.ToolTip>   

                           

 <Button Content="Mouse over me" Width="150" Height="30"  
        Canvas.Top="10" Canvas.Left="10">  
    <ToolTipService.ToolTip >   
        <ToolTip Content="Hello! I am a ToolTip."   
        HorizontalOffset="10" VerticalOffset="20"/>  
    </ToolTipService.ToolTip>  
</Button>                                            


Then if you run the application and hover the mouse over the button control, the output looks as in Figure 2.

                                    ToolTip Service
                                                       

Creating a Fancy Tooltip

The ToolTip content can be any control and multiple controls. The code snippet in Listing 4 creates aToolTip with an image and text in it. 

          <!-- Create a button -->  
<Button Content="Mouse over me" Width="150" Height="30"   
        Canvas.Top="50" Canvas.Left="20">  
    <!-- Create a tooltip by using the ToolTipService -->  
    <ToolTipService.ToolTip >  
        <ToolTip HorizontalOffset="0" VerticalOffset="0">  
            <!-- Add a StackPanel to the tooltip content -->  
            <StackPanel Width="250" Height="150">  
                <!-- Add an image -->  
                <StackPanel.Background>  
                    <ImageBrush ImageSource="Garden.jpg"  
                                Opacity="0.4"/>  
                </StackPanel.Background>  
                <!-- Add a text block -->  
                <TextBlock >  
                    <Run Text="This is a tooltip with an image and text"  
                        FontFamily="Georgia" FontSize="14" Foreground="Blue"/>  
                </TextBlock>  
            </StackPanel>  
        </ToolTip>  
    </ToolTipService.ToolTip>  
</Button>                                       


The new tooltip looks as :

                  Creating a Fancy Tooltip
                                     

 

READ MORE

The XAML Toolbar element represents a window toolbar. A ToolBar control is a group of controls that are typically related in functionality. A typical ToolBar is a toolbar in Microsoft Word and Visual Studio where you see File Open, Save and Print buttons. 

This article discusses basic components of ToolBar controls in WPF and how to use them in your applications. 

Creating a Toolbar

The ToolBar element in XAML represents a WPF ToolBar control. 

<ToolBar />  
The code snippet in Listing 1 creates a ToolBar control and sets its width and height properties. You may place any control on a ToolBar but typically buttons are used. A ToolBar sits on a ToolBarTray. The code snippet in Listing 1 adds three buttons to the ToolBar and places a ToolBar on a ToolBarTray.
<ToolBarTray Background="DarkGray" Height="30" VerticalAlignment="Top">  
  
<ToolBar Name="MyToolbar" Width="200" Height="30" >  
    <Button Background="LightSkyBlue" Content="Open" />  
    <Button Background="LightSkyBlue" Content="Close" />  
    <Button Background="LightSkyBlue" Content="Exit" />  
</ToolBar>  
  
</ToolBarTray>  
                                                      Listing 1


The output looks as in Figure 1. 

         window
                                                      Figure 1

Adding ToolBar Button Click Event Handlers

The best part of WPF is that these buttons are WPF Button controls so you have a choice to use them on any other button. You may format them the way you like. You may add a click event handler to them and so on. 

The code snippet in Listing 2 adds click event handlers to all three ToolBar buttons. 
<ToolBar Name="MyToolbar" Width="200" Height="30"  >  
    <Button Background="LightSkyBlue" Content="Open" Name="OpenButton" Click="OpenButton_Click"  />  
    <Button Background="LightSkyBlue" Content="Close" Name="CloseButton" Click="CloseButton_Click"  />  
    <Button Background="LightSkyBlue" Content="Exit" Name="ExitButton" Click="ExitButton_Click"   />  
 </ToolBar>  
                                                      Listing 2

On these button click event handlers, you would want to write the code you want to execute when these buttons are clicked. For example, I show a message when these buttons are clicked. The code for these button click event handlers is as in Listing 3.
private void OpenButton_Click(object sender, RoutedEventArgs e)  
{  
    MessageBox.Show("Open button is clicked.");  
}  
  
private void CloseButton_Click(object sender, RoutedEventArgs e)  
{  
    MessageBox.Show("Close button is clicked.");  
}  
  
private void ExitButton_Click(object sender, RoutedEventArgs e)  
{  
    MessageBox.Show("Exit button is clicked.");  
}  
                                                      Listing 3

If you click on the Open button, you will see Figure 2 as output. 

                                    button
                                                      Figure 2

Adding Images to ToolBar Buttons 

Usually ToolBars look nicer than just displaying text. In most cases, they have icons. Displaying an Icon image on a button is simply placing an Image control as the content of a Button. The code snippet in Listing 4 changes the Button contents from text to images. 
<ToolBarTray Background="DarkGray" Height="30" VerticalAlignment="Top">  
    <ToolBar Name="MyToolbar" Width="200" Height="30" Background="LightCoral" >  
        <Button Name="OpenButton" Click="OpenButton_Click">  
            <Image Source="Images\camera.png" />  
         </Button>  
        <Button Name="CloseButton" Click="CloseButton_Click">  
            <Image Source="Images\ctv.png" />  
        </Button>  
        <Button Name="ExitButton" Click="ExitButton_Click" >  
            <Image Source="Images\find.png" />  
        </Button>  
    </ToolBar>  
</ToolBarTray>  
                                                      Listing 4

The new ToolBar looks as in Figure 3.

                    ToolBar
                                                      Figure 3

Adding Separators to a ToolBar

You may use a Separator control to give your ToolBar buttons a more prominent look. The code snippet in Listing 4 adds a few extra buttons and a few separators to a ToolBar.
<ToolBarTray Background="DarkGray" Height="30" VerticalAlignment="Top">  
    <ToolBar Name="MyToolbar" Width="180" Height="30" Background="LightCoral" >  
        <Separator />  
        <Button Name="OpenButton" Click="OpenButton_Click">  
            <Image Source="Images\camera.png" />  
         </Button>  
        <Button Name="CloseButton" Click="CloseButton_Click">  
            <Image Source="Images\ctv.png" />  
        </Button>  
        <Button Name="ExitButton" Click="ExitButton_Click" >  
            <Image Source="Images\find.png" />  
        </Button>  
        <Separator Background="Yellow" />  
        <Button >  
            <Image Source="Images\award.png" />  
        </Button>  
        <Button >  
            <Image Source="Images\cuser.png" />  
        </Button>  
        <Button >  
            <Image Source="Images\next.png" />  
        </Button>  
        <Button >  
            <Image Source="Images\code.png" />  
        </Button>  
        <Separator />  
    </ToolBar>  
</ToolBarTray>  
                                                      Listing 5

The ToolBar with separators looks as in Figure 4. Also, if you notice there is a drop array that is available when buttons do not fit in a ToolBar. If you click on that, you will see the rest of the buttons.

   
         fit in a ToolBar
                                                      Figure 4

Summary

In this article, I discussed how to use a ToolBar control in WPF and C#.

READ MORE
...