Jun 302012
 
 June 30, 2012  Posted by at 10:35 am Uncategorized, WinRT  Add comments

Right! I just joined up on MSDN and noticed a question where other developers were asking for a super simple , ie. strawman example, example of how to add data in a Metro App.I actually also had some minor issues with this a few weeks ago, after spending some time with Web apps it’s surprising how fast you forget your data-binding skills in WPF. I also happen to know that IObservableCollection didn’t exist in an earlier Windows 8 version, so if you google adding data you will get some really weird results. Anyways, the question on MSDN asked for a simple example, so I took the time earlier today to create one, hoping to help others as I sure have gotten a lot of help myself from forums such as MSDN and Stackoverflow. As always, please let me know if you have a better way, or if you can make my code sweeter 😉

You can download the example here, and use it as you please

Example with Usercontrol
Does the exact same thing, and looks the same.
 

As you see, it is a VERY basic example 😉

Comments:
Databinding
I used databinding as the natural step (many would argue) is to use the designpattern MVVM, by using databinding the View wont be tightly bound to the viewmodel and model, which provides easier testing, cleaner code and it is easier to change the view later on (or let somebody else do it altogether). But since a simple example was asked for, I haven’t used MVVM, just the databindning that I consider to be a good (best) practice.

Notifying change
Classes have to implement the INotifyPropertChanged interface, but our friends at the Metro lab have been so kind and provided an example of a helper class , BindableBase (found in the Metro templates in the Common folder). This helper class makes you code more readable, so I would recommend you use it. The interface does what it says, it notifies that something has changed. And for a collection to also know this, you would have to use IObservableCollection which uses the INotifyCollectionChanged , the collection version of the INotifyPropertChanged.

XAML

[sourcecode language=”XML”]
<Page
x:Class="AddDataStrawmanExample.MainPage"
IsTabStop="false"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:AddDataStrawmanExample"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">

<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}" >
<StackPanel Orientation="Horizontal" >
<ListView x:Name="AllItemsView" Width="200" Margin="40,20,0,0" Height="400" VerticalAlignment="Top" Background="DarkGray" ItemsSource="{Binding Persons}">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Path=Name}"></TextBlock>
<TextBlock TextWrapping="Wrap" Text="{Binding Path=About}"></TextBlock>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<StackPanel Width="200" Margin="20,50,0,0" Height="200" VerticalAlignment="Top">
<TextBlock>Name</TextBlock>
<TextBox Text="{Binding NewPerson.Name, Mode=TwoWay}"></TextBox>
<TextBlock>About</TextBlock>
<TextBox Text="{Binding NewPerson.About, Mode=TwoWay}"></TextBox>
<Button VerticalAlignment="Top" Margin="30" Width="130" Click="Button_Click_1">Add</Button>
</StackPanel>
</StackPanel>
</Grid>
</Page>

[/sourcecode]

Code

[sourcecode language=”csharp”]

using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using Windows.Foundation.Metadata;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace AddDataStrawmanExample
{
public sealed partial class MainPage : Page
{
private readonly ObservableCollection<Person> _persons = new ObservableCollection<Person>();

public ObservableCollection<Person> Persons
{
get { return _persons; }
}

public MainPage()
{
InitializeComponent();
AddPeopleToList();
CreateNewPerson();
}

private void AddPeopleToList()
{
_persons.Add(new Person {Name = "Iris", About = "Developer that loves Metro style"});
_persons.Add(new Person {Name = "Paul", About = "DBA with a thing for SQL Server 2012"});
}

public Person NewPerson { get; set; }

private void CreateNewPerson()
{
NewPerson = new Person();
}

private void AddNewPerson()
{
Persons.Add(new Person {Name = NewPerson.Name, About = NewPerson.About});
}

private void Button_Click_1(object sender, RoutedEventArgs e)
{
if (NewPerson != null)
{
AddNewPerson();
}
}
}

public class Person : BindableBase
{
private string _name = string.Empty;

public string Name
{
get { return _name; }
set { SetProperty(ref _name, value); }
}

private string _about;

public string About
{
get { return _about; }
set { SetProperty(ref _about, value); }
}
}

[WebHostHidden]
public abstract class BindableBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;

protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName] String propertyName = null)
{
if (Equals(storage, value)) return false;

storage = value;
OnPropertyChanged(propertyName);
return true;
}

protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChangedEventHandler eventHandler = PropertyChanged;
if (eventHandler != null)
{
eventHandler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}

[/sourcecode]

  3 Responses to “Simple example (downloadable): adding data (WinRT / Metro App) using data bindning in XAML”

  1. I would love to see this project i VB.NET.
    My C# skills is nearly non-existant.

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)

What is 15 + 9 ?
Please leave these two fields as-is:
IMPORTANT! To be able to proceed, you need to solve the following simple math (so we know that you are a human) :-)