Data binding – loaded

Back to code talks, yay! The last two posts were all about my daily adventures and experience (boring! 😡 ). FINALLY, we’re back to talk about code again. Okay, lemme see what I did wrong on the last post. As it seems because of MVVM’s steep learning curve a lot of people complained me they are not getting stuff properly in their head. So, let’s make it going. Shall we? Let’s break down stuffs a bit.

Let’s get into Data Binding a bit more. What’s data binding. If we remember our very own View-Model-ViewModel then data binding is what shows a Model’s properties on view. What am I meaning actually? Lets think of a data source that provides a list of persons to an app’s view. So, the model would contain a person’s basic properties, like name, age, height etc. A very important point to ponder here is model is not always the data source itself, it is the template of data in most of the times. So, its properties gets shown in the view i.e. in this case a person’s name, age, height would be shown. And thats in the simplest sense binding. It allows the view to form a bond with the model. 🙂 Trust me, that’s the simplest way I can describe data binding.

So, for all the people who are reading this, let me utter the words of  Jesse Liberty,

  • Data binding is not hard to understand
  • Neither hard to implement

SO, DONT RUN AWAY MAN! YOU ARE BETTER THAN THIS!

So, lets get into it. As this is one of the posts of my current series of MVVM I would definitely keep it on track of it. Lets start with a very basic view.

 <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <!--TitlePanel contains the name of the application and page title-->
        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock x:Name="ApplicationTitle" Text="Data Bidning Loaded" Style="{StaticResource PhoneTextNormalStyle}" />
            <TextBlock x:Name="PageTitle" Text="DataBinding" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
        </StackPanel>

        <!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <TextBox Height="70" HorizontalAlignment="Left" Margin="0,130,0,0" Name="Name" Text="Name" VerticalAlignment="Top" Width="450" />
            <TextBox Height="72" HorizontalAlignment="Left" Margin="0,206,0,0" Name="Age" Text="Age" VerticalAlignment="Top" Width="450" />
            <TextBox Height="72" HorizontalAlignment="Left" Margin="0,284,0,0" Name="Height" Text="Height" VerticalAlignment="Top" Width="450" />
        </Grid>
    </Grid>

Before we get into what we wrote let’s have a peel how it looks

DataBindingSimple1

Pretty basic ha? We need basic for this stage. So, if you look into the view you will see we practically did nothing. We imported three textbox controls and named them Name, Age and Height and filled them up with the same text. Even simple might get blushed seeing this. Cause this is simpler than the word simple. 😛

View is done, next we need a model. It’s gonna be a simple one too. Lets look our simplest Person model.

namespace DataBindingSimple
{
    class PersonModel
    {
        public string Name { get; set; }
        public string Age { get; set; }
        public string Height { get; set; }
    }
}

For the sake of the simplicity we’re gonna use the .cs file attached with the view i.e. the MainPage.xaml.cs here. We’re not gonna create  a seperate viewmodel for now as our purpose is to understand data binding properly first.

Lets see that first

namespace DataBindingSimple
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor

        PersonModel _personModel;

        public MainPage()
        {
            InitializeComponent();
            Loaded += MainPage_Loaded;

        }

        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            _personModel = new PersonModel()
            {
                Name="Prateek",
                Age="23",
                Height="5.5"
            };

            SetDataContext();

        }

        private void SetDataContext()
        {
            ContentPanel.DataContext = _personModel;
        }

    }
}

Well, if we look into what we have just wrote, we’ll see there’s nothing new here. We added a PersonModel object as the DataContext of ContentPanel in the MainPage Loaded event. Wait, wait, wait, DataContext? What on god’s name is that?

To understand the concept of DataContext is to understand where the data comes from to the view. Obviously the data source and what it looks like or what is the template of the data. Of course its our model. Applying  a DataContext to something is to explicitly declare that the data that would be shown in the control comes from that DataContext. If you understand what Im saying then in the simplest sense DataContext is the source of the data. It can be a list, database object, a simple object like we used here. As long as it has data in the template we want , I mean in the model we described, we don’t have to worry about the view. 🙂
So, what we did here, we created a simple PersonModel object and declared it as DataContext of ContentPanel. Why? Because ContentPanel holds the three textboxes we want to show our data. So, the data should go there and as the ContentPanel is the container of those three textboxes it’s awarded the DataContext. Seems a bit clear now?

Is it supposed to work now? Shall we see my name, age and height in the three textboxes in the view now? The answer is obviously NO! We won’t. Why?
BECAUSE WE DIDN’T BIND THE DATA, DUH!

So, lets bind the data, shall we? Lets see how we bind the three properties of PersonModel in the three textboxes in the view. As we will only change the ContentPanel, lets see it below

        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <TextBox Height="70" HorizontalAlignment="Left" Margin="0,130,0,0" Name="Name" Text="{Binding Name}" VerticalAlignment="Top" Width="450" />
            <TextBox Height="72" HorizontalAlignment="Left" Margin="0,206,0,0" Name="Age" Text="{Binding Age}" VerticalAlignment="Top" Width="450" />
            <TextBox Height="72" HorizontalAlignment="Left" Margin="0,284,0,0" Name="Height" Text="{Binding Height}" VerticalAlignment="Top" Width="450" />
        </Grid>

The only thing that has changed is the text property of all the three textboxes. As we wanted to show the name property of the model in the first textbox we wrote:

<TextBox Height="70" HorizontalAlignment="Left" Margin="0,130,0,0" Name="Name" Text="{Binding Name}" VerticalAlignment="Top" Width="450" />

Look into the snippet Text={Binding Name}. Here Binding Name means we are binding the name property of the DataContext to the textbox. And what was the DataContext? Yes! The PersonModel object we assigned as DataContext a while ago.

Let’s see whether it works or not.

DataBindingSimple2

Yay! it does! So, you see Data Binding is practically very very easy. All you need to know is where is to bind something and what to bind. 🙂

I really wanted to talk a bit more but as I see long tutorials kind of takes people’s interest away from it now – a – days. So, thats it for today.

Next, we’re gonna talk about

  • Data Binding with INotifyPropertyChanged
  • Data Binding Modes
  • Element Binding
  • Data Converters

Don’t worry, I wont write these in a single one of course, learned my lesson from the last one. I would try to break these up into short ones.

So, until the next one, ciao!

5 thoughts on “Data binding – loaded

  1. i have little question. Its looks exactly like Observer design pattern . Is it built on observer pattern or its different than that? i have some beginner knowledge of OOP design pattern. i may be wrong.

    1. I didn’t actually get the context you’re talking, data binding or MVVM. :\
      But if you’re talking about MVVM, observer do holds certain similarity but the thing that matters here Observer’s prime directive is to observe and provide. And on the other hand we just cant put MVVM as only a design pattern, rather it’s prime directive is to separate code and design.

      Hope this makes sense a bit. 🙂 And since you know observer pattern why don’t you write a blog on it brother? Share the light. 🙂

Leave a Reply to Fazle Rabby Tanzil Cancel reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s