(X) Hide this
    • Login
    • Join
      • Generate New Image
        By clicking 'Register' you accept the terms of use .

Tip: How to bind an object's property to a control's property?

(3 votes)
Martin Mihaylov
Martin Mihaylov
Joined Oct 29, 2007
Articles:   50
Comments:   70
More Articles
0 comments   /   posted on Sep 09, 2008
Categories:   Data Binding

If you want to bind an object's property to a control's property you can do it the following way.First let's create the object taht the control will bind to (for example a class called Book):

public class Book
    public string Title { get; set; }
    public string Description { get; set; }

After that define your control in the Xaml (a TextBlock for example):

<TextBlock x:Name="MyText" Text="{Binding Title}"></TextBlock>

Using the binding syntax we bind the Text property to the Title property of the Book object. In the codebehind we create an instance of the Book object and set the DataContext of the control to it:

Book myBook = new Book();
myBook.Title = "Silverlight book";
myBook.Description = "A book about Silverlight.";
MyText.DataContext = myBook;


This can also be done entirely in C#, using the :

TextBlock myText = new TextBlock();
Book myBook = new Book();
myBook.PublishDate = DateTime.Now;
Binding binding = new Binding("Title");
binding.Source = myBook;
myText.SetBinding( TextBlock.TextProperty, binding );
LayoutRoot.Children.Add( myText );


We pass the name of the property we want to bind to as a parameter to the constructor of the Binding class. After that we set the source of the binding to the desired object and set the binding to the Text property of the TextBlock control.

That's it!



No comments

Add Comment

Login to comment:
  *      *