WPF: Binding to a single object

This entry is part 24 of 54 in the series Learn WPF

In classic data binding scenario, it usually involves elements that are bound to pure data in the code or from the database.

Here, we look at an XAML file getting some of its data from a Person object.

<Window x:Class="SingleObject1.MainWindow"
        Title="MainWindow" Height="350" Width="525">
        <TextBlock Text="{Binding Name}" FontSize="{Binding FontSize}"/>
        <TextBlock Text="{Binding Age}" />

using System.Windows;

namespace SingleObject1
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
        class Person
            public string Name { get; set; }
            public int Age { get; set; }
            public int FontSize { get; set; }

        public MainWindow()

            Person person = new Person { Name = "Miley Cyrus", Age = 21, FontSize = 24 };
            DataContext = person;

There are 3 properties in this Person object.  The Name, Age and also Fontsize.

In line 22, we have DataContext = person.  You could say that when XAML is ran, some of the data context of the elements in XAML file will be retrieved from the Person object.

The output is as below:





Series Navigation<< WPF: Binding slider and textbox
WPF: Simple combobox data binding >>

Leave a comment

Leave a Reply