Skip Navigation LinksHome / Tips / View Tip

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

+ Add to SilverlightShow Favorites
0 comments   /   posted by Martin Mihaylov on Sep 09, 2008
(3 votes)
Categories: 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!



Comments RSS RSS
No comments

Add Comment


Please add 2 and 7 and type the answer here:

Help us make SilverlightShow even better and win a free t-shirt. Whether you'd like to suggest a change in the structure, content organization, section layout or any other aspect of SilverlightShow appearance - we'd love to hear from you! Need a material (article, tutorial, or other) on a specific topic? Let us know and SilverlightShow content authors will work to have that prepared for you. (hide this)