EDN Admin
Well-known member
Download the sample project seen in this video.
<TextBox Text="{Binding SampleUserName, Mode=TwoWay}" />Data binding is one of the fundamental concepts for good Windows Phone application design but can be difficult to grasp for newcomers. The core concept is this: No one wants to manually update the user interface elements. I want my UI to automatically reflect the state of my application and data binding helps us do this. We can work exclusively on our Windows Phone UI, bind the values in the UI and then work on the inner logic of the application knowing that all the updates are being reflected to the user. Because of the power in the model you see in this video and post, there are some really great "fringe" benefits in terms of interaction and design that we get along with the core benefits.
So lets build our first data binding. By a happy coincidence, this can also be our first ViewModel from scratch.
I use Visual Studio snippets in the video and in "real life" because its substantially faster and I have a very poor memory. You can download the notify property snippets I used here. Just extract them into your "DocumentsVisual Studio 2012Code SnippetsVisual C#My Code Snippets" folder and you should be ready to go.
As a "first steps" post, were going to go through how to build a data binding step by step. To see this model in action, just open up a new
My First Data Binding
In our app, lets create a new ViewModel. I right-clicked in the ViewModel folder and went to "App -> Class..." and created just an empty Class file named "SampleViewModel.cs". This class now looks like this:
class SampleViewModel
{
}
We update it to implement the INotifyPropertyChanged event by declaring that interface and using the "notifyInterface" snippet. Hit Alt-Shift-F10 to resolve any refrerences (specifically the System.ComponentModel) and our code should now look like this:
public class SampleViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Now we can just start creating properties we want to see reflected in our UI. Using our "notifyProp" snippet, we can quickly create a property like the string SampleUserName.
private string _sampleUserName = "";
public string SampleUserName
{
get { return _sampleUserName; }
set
{
_sampleUserName = value;
NotifyPropertyChanged("SampleUserName");
}
}
Now our property is ready to be bound to our XAML.
Define Your Data Context
This part can be skipped for brevity, but I wanted to add it to make sure that there is a complete and comprehensive solution here.
Before our XAML can bind to this property, we need to make the ViewModel visible to our XAML. So we will declare our ViewModel as a static object in our App.xaml.cs
private static SampleViewModel _sampleVM { get; set; }
public static SampleViewModel SampleVM
{
get{
if (_sampleVM == null)
_sampleVM = new SampleViewModel();
return _sampleVM;
}
}
Then we can set the data context when our XAML view initializes. In the MyView.xaml.cs (also called the "code behind), we can add to the constructor:
public MyView()
{
InitializeComponent();
this.DataContext = App.SampleVM;
}
This way we could have the same ViewModel driving multiple Views. This is particularly valuable for a Master-Detail scenario in which we have one View dedicated to showing a list of items and another View for editing or looking at an item detail. With this method, we can maintain a single ViewModel and simply update which item has been selected.
XAML Binding
With our viewmodel defined and our notify properties set up, all we need to do is bind to our XAML UI control. Then any updates we make to our property back in the ViewModel will automatically update in the XAML UI.
<TextBox Text="{Binding SampleUserName}" />
And if we wanted changes to the UI to be updated back in our ViewModel, we just set our binding to "TwoWay"
<TextBox Text="{Binding SampleUserName, Mode=TwoWay}" />
Binding, Sample Data, and Design
In addition to helping us build manageable code with a simple model for XAML UI updates, binding allows us to build our app interfaces in a way that is fast and powerful. Instead of run-view-tweak, run-view-tweak, we can explore design options and do most of our design right inside our tooling without running the application. In fact, if you follow the steps here, you can actually build much of the interaction and XAML of an application up before you start building the logic. The result is the opportunity for a workflow that supports design-driven user-focused application creation.
For this, were going to move away from our SimpleViewModel with its single property and into a real-world example that
focuses on binding with real-world data. To follow along in this example, download this slightly modified version of the LongListSelector Infinite Scroll example for Windows Phone.
Because were working with sample data, we want to open the project in Blend.
Youll get a dialog box that allows you to name your data source and select a class from which Blend will generate the data.
Blend will do a "best guess" on what data is in there based on the data types. String will default to lorem ipsum sample text, and int will generate a number, an ObservableCollection will result in a generated list of sample objects. All this data will be saved as a XAML resource file in the SampleData folder. To create bindings for these objects, all we would have to do is drag the object from our Data tab to an control in our "Objects and Timeline" tab.
We could go into this file and edit the data to be something that is a little more realistic for our application. In fact, this is exactly what Ive done. For this Twitter app, I added some actual tweets from my timeline as sample data. To see this click on the eye icon next to the "resultListBox".
And now we can see the sample data and how it will look in the application.
Here is where it gets really fun: Right-click on the resultListBox and select "Edit Additional Templates -> Edit ItemTemplate -> Edit Current".
This will take you to a XAML DataTemplate where we can define, in real time and against real data, how we want our items to be displayed. We could give our tweet text a height limit and tell it to use ellipses and see that reflected instantly in our design.
<TextBlock Text="{Binding Tweet}"
MaxHeight="40"
TextTrimming="WordEllipsis" />
As you can see, this is an incredibly powerful way to design and build applications for Windows Phone and it is all made possible by DataBinding.
View the full article
<TextBox Text="{Binding SampleUserName, Mode=TwoWay}" />Data binding is one of the fundamental concepts for good Windows Phone application design but can be difficult to grasp for newcomers. The core concept is this: No one wants to manually update the user interface elements. I want my UI to automatically reflect the state of my application and data binding helps us do this. We can work exclusively on our Windows Phone UI, bind the values in the UI and then work on the inner logic of the application knowing that all the updates are being reflected to the user. Because of the power in the model you see in this video and post, there are some really great "fringe" benefits in terms of interaction and design that we get along with the core benefits.
So lets build our first data binding. By a happy coincidence, this can also be our first ViewModel from scratch.
I use Visual Studio snippets in the video and in "real life" because its substantially faster and I have a very poor memory. You can download the notify property snippets I used here. Just extract them into your "DocumentsVisual Studio 2012Code SnippetsVisual C#My Code Snippets" folder and you should be ready to go.
As a "first steps" post, were going to go through how to build a data binding step by step. To see this model in action, just open up a new
My First Data Binding
In our app, lets create a new ViewModel. I right-clicked in the ViewModel folder and went to "App -> Class..." and created just an empty Class file named "SampleViewModel.cs". This class now looks like this:
class SampleViewModel
{
}
We update it to implement the INotifyPropertyChanged event by declaring that interface and using the "notifyInterface" snippet. Hit Alt-Shift-F10 to resolve any refrerences (specifically the System.ComponentModel) and our code should now look like this:
public class SampleViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Now we can just start creating properties we want to see reflected in our UI. Using our "notifyProp" snippet, we can quickly create a property like the string SampleUserName.
private string _sampleUserName = "";
public string SampleUserName
{
get { return _sampleUserName; }
set
{
_sampleUserName = value;
NotifyPropertyChanged("SampleUserName");
}
}
Now our property is ready to be bound to our XAML.
Define Your Data Context
This part can be skipped for brevity, but I wanted to add it to make sure that there is a complete and comprehensive solution here.
Before our XAML can bind to this property, we need to make the ViewModel visible to our XAML. So we will declare our ViewModel as a static object in our App.xaml.cs
private static SampleViewModel _sampleVM { get; set; }
public static SampleViewModel SampleVM
{
get{
if (_sampleVM == null)
_sampleVM = new SampleViewModel();
return _sampleVM;
}
}
Then we can set the data context when our XAML view initializes. In the MyView.xaml.cs (also called the "code behind), we can add to the constructor:
public MyView()
{
InitializeComponent();
this.DataContext = App.SampleVM;
}
This way we could have the same ViewModel driving multiple Views. This is particularly valuable for a Master-Detail scenario in which we have one View dedicated to showing a list of items and another View for editing or looking at an item detail. With this method, we can maintain a single ViewModel and simply update which item has been selected.
XAML Binding
With our viewmodel defined and our notify properties set up, all we need to do is bind to our XAML UI control. Then any updates we make to our property back in the ViewModel will automatically update in the XAML UI.
<TextBox Text="{Binding SampleUserName}" />
And if we wanted changes to the UI to be updated back in our ViewModel, we just set our binding to "TwoWay"
<TextBox Text="{Binding SampleUserName, Mode=TwoWay}" />
Binding, Sample Data, and Design
In addition to helping us build manageable code with a simple model for XAML UI updates, binding allows us to build our app interfaces in a way that is fast and powerful. Instead of run-view-tweak, run-view-tweak, we can explore design options and do most of our design right inside our tooling without running the application. In fact, if you follow the steps here, you can actually build much of the interaction and XAML of an application up before you start building the logic. The result is the opportunity for a workflow that supports design-driven user-focused application creation.
For this, were going to move away from our SimpleViewModel with its single property and into a real-world example that
focuses on binding with real-world data. To follow along in this example, download this slightly modified version of the LongListSelector Infinite Scroll example for Windows Phone.
Because were working with sample data, we want to open the project in Blend.
- Open up the MainPage.xaml file and go to the Data tab at the top right corner.
- Select the project data store and click on the "Create sample data -> Create Sample Data From Class" button.
Youll get a dialog box that allows you to name your data source and select a class from which Blend will generate the data.
Blend will do a "best guess" on what data is in there based on the data types. String will default to lorem ipsum sample text, and int will generate a number, an ObservableCollection will result in a generated list of sample objects. All this data will be saved as a XAML resource file in the SampleData folder. To create bindings for these objects, all we would have to do is drag the object from our Data tab to an control in our "Objects and Timeline" tab.
We could go into this file and edit the data to be something that is a little more realistic for our application. In fact, this is exactly what Ive done. For this Twitter app, I added some actual tweets from my timeline as sample data. To see this click on the eye icon next to the "resultListBox".
And now we can see the sample data and how it will look in the application.
Here is where it gets really fun: Right-click on the resultListBox and select "Edit Additional Templates -> Edit ItemTemplate -> Edit Current".
This will take you to a XAML DataTemplate where we can define, in real time and against real data, how we want our items to be displayed. We could give our tweet text a height limit and tell it to use ellipses and see that reflected instantly in our design.
<TextBlock Text="{Binding Tweet}"
MaxHeight="40"
TextTrimming="WordEllipsis" />
As you can see, this is an incredibly powerful way to design and build applications for Windows Phone and it is all made possible by DataBinding.
View the full article