ListView in WinJS based Windows Store Application

In 2012 I wrote a post List View Data Binding in Windows 8 JavaScript Metro Application. If you follow along this post some of the code will not work. So I decided to write a post again on working with ListView in WinJS. There are three simple steps to work with the ListView.

Step1: Create the Data Source

Let us use JavaScript array as the data source. In the real application you may want to call a service to fetch the data and create the data source. The JavaScript array is created as follows:

 


var MovieData = [
                            { Name: 'Abduction', Photo: 'images/abduction.jpg' },
                            { Name: 'A Better Life', Photo: 'images/abetterlife.jpg' },
                            { Name: 'A Dangerous Method ', Photo: 'images/adangerousmethod.jpg' },
                            { Name: 'Begineers', Photo: 'images/beginners.jpg' },
                            { Name: 'Bell Flower', Photo: 'images/bellflower.jpg' },
                            { Name: 'Black Thorn', Photo: 'images/blackthorn.jpg' },
                            { Name: 'Abduction', Photo: 'images/abduction.jpg' },
                            { Name: 'A Better Life', Photo: 'images/abetterlife.jpg' },
                            { Name: 'A Dangerous Method ', Photo: 'images/adangerousmethod.jpg' },
                            { Name: 'Begineers', Photo: 'images/beginners.jpg' },
                            { Name: 'Bell Flower', Photo: 'images/bellflower.jpg' },
                            { Name: 'Black Thorn', Photo: 'images/blackthorn.jpg' },
                            { Name: 'Abduction', Photo: 'images/abduction.jpg' },
                            { Name: 'A Better Life', Photo: 'images/abetterlife.jpg' },
                            { Name: 'A Dangerous Method ', Photo: 'images/adangerousmethod.jpg' },
                            { Name: 'Begineers', Photo: 'images/beginners.jpg' },
                            { Name: 'Bell Flower', Photo: 'images/bellflower.jpg' },
                            { Name: 'Black Thorn', Photo: 'images/blackthorn.jpg' },
                   ];

We cannot set an array directly as the data source of ListView. So to set array as the data source we need to convert the array as List object. MovieArray can be converted to the List object as shown follows:

 


var dataList = new WinJS.Binding.List(MovieData);

Step2: Create the Template

Once the data source is in placed we need to decide how to display the data in the ListView. Using the Template we decide the way ListView item will be rendered. Binding template can be created setting data-win-control attribute of a div to WinJS.Binding.Template. We are displaying and Photo from the data source. You need to make sure to use exact the same property name as it is in the data source.

 


<div id="movieitemtemplate"
         data-win-control="WinJS.Binding.Template">
        <div data-win-bind="innerText:Name"
             style="height:20px;">
        </div>
        <img data-win-bind="src:Photo"
             style="width:200px;height:150px;" />
    </div>


Step3: Create the ListView

A div can be converted to a ListView setting data-win-control property to WinJS.UI.ListView. We are setting the itemTemplate to movieitemtemplate which we created in the previous step.

 


<div id="MovieListView"
         data-win-control="WinJS.UI.ListView"
         data-win-options="{itemTemplate: select('#movieitemtemplate')}">
    </div>


After the ListView is created last step is to bind the ListView to the data source. We have already created List using the JavaScript array. To bind set data source of the list as the itemDataSource of the ListView. It is shown as follows:

 

args.setPromise(WinJS.UI.processAll());
            var dataList = new WinJS.Binding.List(MovieData);
            var MovieList = document.getElementById('MovieListView').winControl;
            MovieList.itemDataSource = dataList.dataSource;


That’s it. These three steps are needed to work with a ListView in WinJS. Hope you like it. Happy coding.

Data Binding and Observable in WinJS

Source code on GitHub

In this post we will learn how to work with the data binding and observable class in the Windows Store application created using WinJS. We will learn to work with

  • Data binding
  • Two way data binding
  • Observable object

By default WinJS

  • Provides one way binding
  • When the data source is updated HTML element gets updated
  • Updated value of HTML element does not update the data source.

Let us start with working with a basic data binding example. So I have a JavaScript object as shown below,


var student = { name: "Dj" };

We can perform data binding in winJS using data-win-bind attribute on the HTML element.

clip_image002

In above code snippet we are using data-win-bind attribute to bind span inner text with the name property of the student object. As of now HTML is very simple and looks like as follows:


<body>
     <div id="welcome">
        Welcome,
        <span id="nameSpan"
              data-win-bind="innerText: name">
        </span>
    </div>

</body>

As the last step of the data binding we need to call WinJS.Binding.processAll() by passing the data source and the target HTML element. Make sure that you call this after the execution of all the activation codes.


    var personDiv = document.querySelector('#nameSpan');
    WinJS.Binding.processAll(personDiv, student);

Essentially we are selecting the element using the document.querySelector and the in the process all function passing the target element and the data source as a data context. By now we have successfully data bind html element to the data source. On running the application you should get output as follows

clip_image002[6]

So far we have done one way binding and if data changes at the data source target element won’t get any notification. We can convert a data context to a binding context using the WinJS.Binding.as. To understand this in better way let us start looking at a problem statement. I have modified the UI as follows,


<body>
    <div id="welcome">
        Welcome,
        <span id="nameSpan"
              data-win-bind="innerText: name">
        </span>
        <br/>
        <input type="text" id="txtInput" />
        <button id="btnUpdataDs">Update DataSource</button>
    </div>

</body>

Now UI look like as follows and when we enter a value in the text box that should update the welcome span.

clip_image002[8]

On the click event of the button we can modify name property as follows


document.querySelector("#btnUpdataDs").onclick = function () {

           var updatedname = document.querySelector('#txtInput').value;
           student.name = updatedname;
        }

When run the application you will find that value of the welcome span is not getting updated. Reason behind is that when data source is getting updated it does not send any notification to the target elements bind to it. WinJS gives us a method to create notification on the data source and convert it to a binding context. You need to use WinJS.Binding.as to create binding context.

So let us modify the above code to perform two way binding,

var personDiv = document.querySelector('#nameSpan');
        WinJS.Binding.processAll(personDiv, student);
        var bindingSource = WinJS.Binding.as(student);
        document.querySelector("#btnUpdataDs").onclick = function () {

           var updatedname = document.querySelector('#txtInput').value;
           bindingSource.name = updatedname;
        }

In above code there is only one extra added line

clip_image002[10]

Now on running the application you will find that when you change the value in text box and click on update data source value of welcome span will also be changed.

clip_image004

WinJS data bind allows us to to do binding of styles as well. Let us go ahead and add one more property to set the color of the text. Updated data source is as follows:

 


   var student = {
        name: "Dj",
        color: "red"
     };

And we can bind color to the welcome span as follows


<span id="nameSpan"
              data-win-bind="innerHTML: name;
               style.background: color ">
        </span>

And we can update value of color as follows

var personDiv = document.querySelector('#nameSpan');
        WinJS.Binding.processAll(personDiv, student);
        var bindingSource = WinJS.Binding.as(student);
        document.querySelector("#btnUpdataDs").onclick = function () {

           var updatedname = document.querySelector('#txtInput').value;
           bindingSource.color = updatedname;
        }

Now let us see that how can we bind to a complex object. We will start with creating a complex object. Working with complex object can be summarized into following steps

  1. Create the class
  2. Add _initObservable method in the constructor of the class
  3. Make class observable by using the WinJS.Class.mix
  4. Create instance of the object
  5. Use bind methods to bind the properties
  6. Use the object in the binding

Let us start with creating a Student class

 


var Student = WinJS.Class.define(
       function()
       {

           this.name = "DJ";
           this.size = "16px";
       },
       {

           _names:
               ["foo", "loo", "koo", "too", "moo", "soo", "aoo", "too", "qoo", "coo"],
           _sizes:
               ["30px", "80px", "40px","20px","35px","67px","43px","23px","54px","12px"],

           _newName: function () {
               this["name"] = this._names[this._randomizeValue(this._names.length)];
               this["size"] = this._sizes[this._randomizeValue(this._sizes.length)];
           },
           _randomizeValue: function (max) {
               return Math.floor((Math.random() * 1000) % max);
           }

       });

In this class we have put two arrays and two functions. In the constructor of the class we are setting default value for name and the size. _newName function will return new name from the array with new size from the size array.

Next we need to add _initObservable inside the constructor. So updated constructor will look like as follows:

 


  var Student = WinJS.Class.define(
       function()
       {
           this._initObservable();
           this.name = "DJ";
           this.size = 16;
       },

Now to make the object observable we need to use WinJS.Class.mix. This can be done as follows:


    WinJS.Class.mix(Student,
    WinJS.Binding.mixin,
    WinJS.Binding.expandProperties({name: "", size: ""})
);

After this step we need to call the bind method on the instance of the Student class. Make sure to create instance in the app.onactivated event handler.

 

            var s = new Student();
            s.bind("name",onNameChange);
            s.bind("size", onSizeChange);

The bind method takes two parameters. First name of the property and second parameter as the function which will define how property will be bind. Below we have function calling on the bind.


function onNameChange (newValue) {
        var span = document.getElementById("nameSpan");
        span.innerText = newValue;
    };

    function onSizeChange (newValue) {
        var span = document.getElementById("nameSpan");
        span.style.fontSize = newValue;
    };

On the HTML markup is bind to properties of Student and there a button. On click event of the button we will call _newName function on the student object to change the name and the font size.


   <div id="welcome">
        Welcome,
        <span id="nameSpan"
              data-win-bind="innerHTML: name;
               style.fontsize: size ">
        </span>
        <br/>
        <button id="btnUpdataDs">Update DataSource</button>
    </div>

On the click event of the button we will call _nameName function as shown below:

document.querySelector("#btnUpdataDs").onclick = function () {

            s._newName();
        }

When you run the application on the click of the button name and size of the name should change. Data binding and the observable are very important components of WinJS and you may want to use them while create app for the Windows Store.

Source code on GitHub

Happy Coding.

Solved Exception in Passing Relative URI to Windows Runtime

While working today on a Windows Store Application I had a requirement to work with URI. Business class was as follows,

 

image

And I created instance of Product class in usual way setting values for both properties. I had put all images in ProductImages folder.

 

image

 

On running application I got following exception that given System.Uri cannot be converted.

image

 

After small research I found that WinRT does not support Relative URI. It only supports Absolute URI.

 

image

 

Now I fixed above problem by converting Relative URI to Absolute URI.

 

image

 

Exception got fixed after changing URI as absolute URI. I hope you find this quick fix useful. Thanks for reading.

Fetching Windows Azure Mobile Services Data in XAML based Windows Store Application

In last post we started learning about Windows Azure Mobile Service in XAML based Windows Store Application. Read it here

In last post we learnt

  • Configuring Window Azure Mobile Service in portal
  • Consuming Windows Azure Mobile Service in Windows Store Application
  • Insert a record from application in Windows Azure Mobile Service data table.

In this post we will take a look on fetching records from table. I recommend you to follow Part 1 of this series here . I will start from where I left in part 1.

Let us design application page. There are two buttons. On click of first button we will fetch all data. On click of second button filtered data will fetched. Let us design application page as following


<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}" >
 <Grid.RowDefinitions>
 <RowDefinition Height="*" />
 <RowDefinition Height="*" />

 </Grid.RowDefinitions>

<StackPanel Orientation="Vertical" Grid.Row="0">
 <Button x:Name="btnFetch" Click="btnFetch_Click_1" Content="Get Data" Height="72" Width="233"/>
 <GridView x:Name="lstBloggers" >
 <GridView.ItemTemplate>
 <DataTemplate>
 <StackPanel Orientation="Horizontal">
 <TextBlock Text="{Binding Name}" />
 <TextBlock Text="{Binding Technology}" />
 </StackPanel>
 </DataTemplate>
 </GridView.ItemTemplate>
 </GridView>
 </StackPanel>
 <StackPanel Orientation="Vertical" Grid.Row="1">
 <StackPanel Orientation="Horizontal">
 <TextBox x:Name="txtSearch" Height="59" Width="436" />
 <Button x:Name="btnFilterfetch" Click="btnFilterfetch_Click_1" Content="Get Filtered Data" Height="72" Width="233"/>
 </StackPanel>
 <ListView x:Name="lstFilterBloggers" Margin="368,20,271,-599">
 <ListView.ItemTemplate>
 <DataTemplate>
 <StackPanel Orientation="Horizontal">
 <TextBlock Text="{Binding Name}" />
 <TextBlock Text="{Binding Technology}" />
 </StackPanel>
 </DataTemplate>
 </ListView.ItemTemplate>
 </ListView>
 </StackPanel>
 </Grid>

Yes this is not one of the best UI we can create but any way creating highly immersive UI is not purpose of this post. Right now UI will look like below image

image

Now to fetch all the records you need to follow following steps

Define Global variables


MobileServiceClient client;
 MobileServiceCollectionView<TechBloggers> items;
 MobileServiceCollectionView<TechBloggers> filteredItems;
 IMobileServiceTable<TechBloggers> bloggerstable;


You need to create mobile service table client in application. That can be created as following


public MainPage()
 {
 this.InitializeComponent();
 MobileServiceClient client = new MobileServiceClient("https://youappurl", "appkey");
 bloggerstable = client.GetTable<TechBloggers>();

 }

&nbsp;

Next you need to create entity class representing table from the Windows Azure Mobile Service. Let us create entity class as following. We are creating entity class TechBloggers.


public class TechBloggers
 {
 public int id { get; set; }
 [DataMember(Name="name")]
 public string Name { get; set; }
 [DataMember(Name = "technology")]
 public string Technology { get; set; }

}

On click event of button you can fetch all data from Mobile Service Table as following


private void btnFetch_Click_1(object sender, RoutedEventArgs e)
 {

items = bloggerstable.ToCollectionView();
 lstBloggers.ItemsSource = items;

}

You can fetch filtered data as following. We are filtering data on search term given in textbox.

private void btnFilterfetch_Click_1(object sender, RoutedEventArgs e)
 {
 filteredItems = bloggerstable.Where
 (blogger => blogger.Technology == txtSearch.Text)
 .ToCollectionView();
 lstFilterBloggers.ItemsSource = filteredItems;

 }

&nbsp;

When you run application you will find all data and filtered data as following

image

In this way we can fetch data from Windows Azure Mobile Service. In next post we will get into update and deletion of record. I hope this post useful. Thanks for reading.

Step by Step working with Windows Azure Mobile Service Data in JavaScript based Windows Store Apps

In my last post I discussed Step by Step working with Windows Azure Mobile Service Data in XAML based Windows Store Apps . In this post we will have a look on working with JavaScript based Windows Store Apps. Last post was divided in two parts. First part was Configure Windows Azure Mobile Service in Portal. You need to follow step 1 from last step to configure Windows Azure Mobile Service Data. To work with this proceed as given in following steps,

  1. Configure Windows Azure Mobile Service in Portal. For reference follow Step 1 of this Blog
  2. Download Windows Azure SDK and install.

Now follow post to work with Windows Azure Mobile Service Data from JavaScript based Windows Store Application.

Create Windows Store Application in JavaScript

Create Blank App from creating Blank App template from JavaScript Windows Store App project tab.

image

After creating project add Windows Azure Mobile Services JavaScript Client reference in project.

image

After adding reference let us go ahead and design app page to add a blogger in table. We are going to put two text boxes and one button. On click event of the button blogger will be inserted as row in data table of Windows Azure Mobile Services.


<body>

 <h2>Adding Record to Windows Azure Mobile Service Data</h2> <br />
 Name : <input id="txtname" type="text" /> <br />
 Technology : <input id="txttechnology" type="text" /> <br /> <br />
 <button id="btnInsert" >Insert Blogger</button>

</body>

Application will look like following,

image

We need to add reference of Windows Azure Mobile Service on HTML as following


<script src="//Microsoft.WinJS.1.0/js/ui.js"></script>
 <script type="text/javascript" src="/MobileServicesJavaScriptClient/MobileServices.js"></script>

Next let us create client for Windows Azure Mobile Service. To create this you need to pass application URL and application Key. Client in JavaScript based application can be created as following


args.setPromise(WinJS.UI.processAll());
 var client = new Microsoft.WindowsAzure.MobileServices.MobileServiceClient(
 "https://appurl",
 "appkey"
 );

Now let us create a proxy table. Proxy table can be created as following and after creating proxy table we can add record in table as following


var bloggerTable = client.getTable('techbloggers');

var insertBloggers = function (bloggeritem) {

bloggerTable.insert(bloggeritem).done(function (item) {
 //Item Added
 });

On click event of button we need to call insertBloggers javascript function.

btnInsert.addEventListener("click", function () {
 insertBloggers({
 name: txtname.value,
 technology: txttechnology.value
 });
 });

On click event of button you should able to insert blogger in Windows Azure Mobile Service Data table. In further post we will learn to perform update, delete and fetch data. I hope you find this post useful. Thanks for reading.

Step by Step working with Windows Azure Mobile Service Data in XAML based Windows Store Apps

In this post we will take a look on working with Windows Azure Mobile Service in XAML based Windows Store Application. We will follow step by step approach to learn goodness of Windows Azure Mobile Service. In first part of post we will configure Windows Azure Mobile Service in Azure portal. In second part of post we will create a simple XAML based Windows Store application to insert records in data table. This is first post of this series and in further posts we will learn other features of Windows Azure Mobile Services.

Configure Windows Azure Mobile Service on Portal

Step 1

Login to Windows Azure Management Portal here

Step 2

Select Mobile Services from tabs in left and click on CREATE NEW MOBILE SERVICE

image

Step 3

In this step provide URL of mobile service. You have two choice either to create mobile service in existing database or can create a new database. Let us go ahead and create a new database. In DATABSE drop down select option of Create New SQL database instance. Select SUBSCRIPTION and REGION from drop down as well.

image

Step 4

On next screen you need to create database. Choose either existing database server or create a new one. You need to provide credential to connect with database servers.

image

Step 5

After Successful creation of mobile services you need to select platform. Let us go ahead and choose Windows Store as platform

image

Step 6

After selecting platform click on Data in menu. After selecting Data click on ADD A TABLE

image

Next you need to provide Table name. You can provide permission on table. There are three options available

  1. Anybody with Application Key
  2. Only Authenticated Users
  3. Only Scripts and Admins

Let us leave default permission level for the table.

image

Step 7

Next click on tables. You will be navigated to table dashboard. When you click on Columns you will find one default created column id. This column gets created automatically. This column must be there in Windows Azure Mobile Service table.

image

On enabling of dynamic schema when you will add JSON objects from client application then columns will get added dynamically.

Create Windows Store Application in XAML

Very first you need to install Windows Azure SDK for Windows Phone and Windows 8.

image

After installing create a Windows Store Application by choosing Blank App template.

image

Before we move ahead to create Windows Store App let us go back to portal and mange App URL and key. You need key and application URL to work with Windows Azure Mobile Services from Windows Store application. You will find key and application URL at the portal.

image

Now go ahead and add following namespaces on MainPage.xaml.cs


using Microsoft.WindowsAzure.MobileServices;
using System.Runtime.Serialization;

Next you need to create entity class representing table from the Windows Azure Mobile Service. Let us create entity class as following. We are creating entity class TechBloggers.


public class TechBloggers
 {
 public int id { get; set; }
 [DataMember(Name="name")]
 public string Name { get; set; }
 [DataMember(Name = "technology")]
 public string Technology { get; set; }

}

After creating entity class go ahead and global variables.


MobileServiceClient client;
 IMobileServiceTable<TechBloggers> bloggerstable;

Once global variable is defined in the constructor of page you need to create instance of MobileServiceClient and MobileServiceTable. Let us go ahead and create that in constructor of the page.


public MainPage()
 {
 this.InitializeComponent();
 MobileServiceClient client = new MobileServiceClient("https://youappurl", "appkey");
 bloggerstable = client.GetTable<TechBloggers>();

 }

Now let us go back and design app page. On XAML let us put two textboxes and one button. On click event of button we will insert bloggers in the table.


<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}" >
 <Grid.RowDefinitions>
 <RowDefinition Height="100" />
 <RowDefinition Height="100" />
 <RowDefinition Height="100" />
 </Grid.RowDefinitions>
 <StackPanel Grid.Row="0" Orientation="Horizontal" Margin="40,40,0,0">
 <TextBlock Text="Name" FontSize="40" />
 <TextBox x:Name="txtName" VerticalAlignment="Top" Width="400" />
 </StackPanel>
 <StackPanel Orientation="Horizontal" Grid.Row="1" Margin="40,40,0,0">
 <TextBlock Text="Technology" FontSize="40" />
 <TextBox x:Name="txtTechnology" VerticalAlignment="Top" Width="400" />
 </StackPanel>

 <Button Grid.Row="2" x:Name="btnInsert" Click="btnInsert_Click_1" Content="Insert Record" Height="72" Width="233" Margin="248,42,0,-14" />

 </Grid>

Application will look like as given in below image. I know this is not best UI. Any way creating best UI is not purpose of this post

image

On click event of button we can insert a record to table using Windows Azure Mobile Services using following code


private void btnInsert_Click_1(object sender, RoutedEventArgs e)
 {

TechBloggers itemtoinsert = new TechBloggers
 {
 Name = txtName.Text,
 Technology = txtTechnology.Text
 };

InserItem(itemtoinsert);

}

InsertItem function is written like following,

private async void InserItem(TechBloggers itemtoinsert)
 {

await bloggerstable.InsertAsync(itemtoinsert);

 }

On click event of button you can insert records in Windows Azure Mobile Service data table. To verify inserted records browse to portal and click on table.

image

In further posts we will learn update, delete and view of the records. I hope you find this post useful. Thanks for reading.

Binding Image with Picture Library Images in Windows Store Application using FileOpenPicker

In this post we will take a look on binding image with Picture Library Images in Windows Store. In this post we will follow following steps

  • User will click on a button
  • On button click user will be select an image from Picture Library
  • Selected image will be bind to image control on the page

Application will behave as following,

image

In XAML based Windows Store Application object of FileOpenPicker allows us to choose files from Picture Library and Document Library. Essentially we will create instance of FileOpenPicker on click event of button and then restrict user to select only images. Once user has selected image, we will bind that Image to image control on the page.

Let us start with designing the page. Page design is very simple with button, image control and two text blocks.


<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
 <Grid.RowDefinitions>
 <RowDefinition Height="100" />
 <RowDefinition Height="*" />
 </Grid.RowDefinitions>
 <TextBlock Text="Select Photo from Picture Library" Margin="15,20,0,0" FontSize="40"/>
 <StackPanel Orientation="Horizontal" Grid.Row="1">
 <Button x:Name="btnFilePickerOpen" Click="btnFilePickerOpen_Click_1" Content="Select Image" Width="303" Height="97" Margin="50,50,0,403"/>
 <StackPanel Orientation="Vertical" Margin="50,50,0,0">
 <Image x:Name="imgSelected" />
 <TextBlock x:Name="txtSelectedImagePath" Margin="30,30,0,0" FontSize="30" />
 </StackPanel>
 </StackPanel>
 </Grid>

On click event of button we will create object of FileOpenPicker and allow user to select an image. We need to follow following steps

  • Create object of FileOpenPicker
  • Select ViewMode. There are two ViewModes available Thumbnail and List. Let us choose Thumbnail for our demo.
  • Provide SuggestedStartLocation. Let us select PicturerLibrary since we want to choose an image. Other options are VideosLibrary, DocumetsLibrary etc.
  • Apply filter. We can apply filters on type of files we will allow user to choose. We are adding file types jpg,jpeg and png.
  • In last step asynchronously we are calling PickSingleFileAsync function and taking reference of selected file in StorageFile.
FileOpenPicker openPicker = new FileOpenPicker();
 openPicker.ViewMode = PickerViewMode.Thumbnail;
 openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
 openPicker.FileTypeFilter.Add(".jpg");
 openPicker.FileTypeFilter.Add(".jpeg");
 openPicker.FileTypeFilter.Add(".png");
 StorageFile file = await openPicker.PickSingleFileAsync();
 if (file != null)
 {

 }
 else
 {

 }

On successful selection of file we need to convert that in image stream and bind that to image control. We are creating instance of BitmapImage and reading file stream in that. After successful reading setting bitmap image as source of image control.


if (file != null)
 {
 txtSelectedImagePath.Text = file.Name;
 var filestream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
 BitmapImage imagetobind = new BitmapImage();
 imagetobind.SetSource(filestream);
 imgSelected.Source = imagetobind;

 }
 else
 {
 txtSelectedImagePath.Text = "Some problem fetching file ";
 }

&nbsp;

This is what all we need to do to fetch an image from picture library and bind it to image control. Full source code of button click is given below,


private async void btnFilePickerOpen_Click_1(object sender, RoutedEventArgs e)
 {
 FileOpenPicker openPicker = new FileOpenPicker();
 openPicker.ViewMode = PickerViewMode.Thumbnail;
 openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
 openPicker.FileTypeFilter.Add(".jpg");
 openPicker.FileTypeFilter.Add(".jpeg");
 openPicker.FileTypeFilter.Add(".png");
 StorageFile file = await openPicker.PickSingleFileAsync();
 if (file != null)
 {
 txtSelectedImagePath.Text = file.Name;
 var filestream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
 BitmapImage imagetobind = new BitmapImage();
 imagetobind.SetSource(filestream);
 imgSelected.Source = imagetobind;

 }
 else
 {
 txtSelectedImagePath.Text = "Some problem fetching file ";
 }
 }

Now when you run application you will able to choose an image from Picture Library and bind it to image control.

image

I hope you find this post useful. Thanks for reading.