Skip to main content

WPF Tutorial - Binding without XAML

The introduction of binding and XAML has made creating user interfaces in .NET a much more enjoyable experience compared to previous incarnations. Binding is such an integral part of the WPF experience that most developers thoroughly understand how to do it in XAML, however what we're going to look at today is how to create a binding using only C# code.
I'm going to build a very basic example application - it has a TextBlock and a TextBox. Whatever is typed into the TextBox, will be reflected in the TextBlock. Here's a screenshot of what I'm talking about:
Example App Screenshot
This application lends itself perfectly to XAML binding, and in fact that's the first way I implemented it.
<Window x:Class="BindingWithoutXAML.MainWindow"
       xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
       xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
       Title="MainWindow"
       Height="350"
       Width="525">
  <Grid Margin="10">
    <Grid.ColumnDefinitions>
      <ColumnDefinition Width="*" />
      <ColumnDefinition Width="10" />
      <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>

    <TextBox x:Name="textBox"
            VerticalAlignment="Center" />

    <TextBlock x:Name="textBlock"
              VerticalAlignment="Center"
              Grid.Column="2"
              Text="{Binding ElementName=textBox, Path=Text,
                       UpdateSourceTrigger=PropertyChanged}" />

  </Grid>
</Window>
You can clearly see my two controls and the binding that links the two. Whenever the Text property of the TextBox changes, the Text property of the TextBlock will be updated. Now let's move the binding to the code-behind.
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
   public MainWindow()
   {
      InitializeComponent();

      // Create a binding object for the Text property of the TextBox.
      Binding binding = new Binding("Text");

      // Set the binding to update whenever the property changes.
      binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;

      // Set the source object of the binding to the TextBox.
      binding.Source = textBox;

      // Add the binding to the TextBlock.
      textBlock.SetBinding(TextBlock.TextProperty, binding);
   }
}
You can definitely see the correlation between the XAML and the C#. The first thing we do is create a Binding object and tell it to bind to the Text property of its source object. We then tell the binding to update the destination property whenever the source property changes. We then give it the actual source object - the one that owns the property "Text". Lastly we set the binding on the destination object and specify the property we'd like to bind to. If we run the application, we'd get the exact same behavior.
It's not always obvious where you'll need to specify bindings in the C# code, but one scenario I've encountered in the past is that my source object doesn't exist right away. Sometimes I need to delay the binding until it does, and XAML doesn't have the ability to wait until the source property exists before creating and applying the binding.

Comments

Popular posts from this blog

FlexBox (combobox+json +Paging)

FlexBox Visit the FlexBox Home Page FlexBox  is a jQuery plugin that is intended to be a very flexible replacement for html textboxes and dropdowns, optionally using ajax to retrieve and bind JSON data. It can be used as a: ComboBox, with optional per-result html templates Suggest box, like Google's search Data-driven type-ahead input box It supports: Auto-completion using local (JSON) or remote (JSON via ajax) data Skinning via css Flexible paging Configurable client-side caching Much more... (see Configuration Options in the documentation) Screenshotflex More demos and code examples

ASP .NET - XML Files

An XML File Here is an XML file named "countries.xml": <?xml version="1.0" encoding="ISO-8859-1"?> <countries> <country>   <text>Norway</text>   <value>N</value> </country> <country>   <text>Sweden</text>   <value>S</value> </country> <country>   <text>France</text>   <value>F</value> </country> <country>   <text>Italy</text>   <value>I</value> </country> </countries> Bind a DataSet to a List Control First, import the "System.Data" namespace. We need this namespace to work with DataSet objects. Include the following directive at the top of an .aspx page: <%@ Import Namespace="System.Data" %> Next, create a DataSet for the XML file and load the XML file into the DataSet when the page is first loaded: <script runat="server"> sub Page_Load if Not Page.IsPos...

SQL JOINS &UNION

SQL JOIN The JOIN keyword is used in an SQL statement to query data from two or more tables, based on a relationship between certain columns in these tables. Tables in a database are often related to each other with keys. A primary key is a column (or a combination of columns) with a unique value for each row. Each primary key value must be unique within the table. The purpose is to bind data together, across tables, without repeating all of the data in every table. Look at the "Persons" table: P_Id LastName FirstName Address City 1 Hansen Ola Timoteivn 10 Sandnes 2 Svendson Tove Borgvn 23 Sandnes 3 Pettersen Kari Storgt 20 Stavanger Note that the "P_Id" column is the primary key in the "Persons" table. This means that  no  two rows can have the same P_Id. The P_Id distinguishes two persons even if they have the same name. Next, we have the "Orders" table: O_Id OrderNo P_Id 1 77895 3 2 44678 3 3 22456 1 4 24562 1 5 34764 15 Note that the "O_...