WPFwiki, wpf, wiki, .net 3.0, windows presentation foundation, FAQ, free resources, solution, development, microsoft Home of the world's largest WPF FAQ
Edit

Category

Data Binding

Edit

Question

How can Expression Blend use DataBinding to a business object?

Edit

Answer

One way to achieve this is to define a class that you will use for your DataContext, then tell the XAML code about it.

Here's the class I want to use:
namespace MyNameSpace {
  public class MyDataContext {
    public string Title { set; get; }
    public string SubTitle { set; get; }
    public MyDataContext(string title, string subTitle) {
      Title = title;
      SubTitle = subTitle;
    }
  }
}


Now, in my XAML file (called MyWindow.xaml and MyWindow.xaml.cs) I need to declare a prefix for the namespace where this class lives (add this as an attribute of the root element):
... xmlns:local="clr-namespace:MyNameSpace" ...


And then tell the root element (in this case, a Window) about the class that I will later be assigning to the DataContext:
<Window.DataContext>
  <local:MyDataContext />
</Window.DataContext>


With this in place, Expression Blend (2.5) now shows the MyDataContext class as the Explicit Data Context for all the elements in the XAML page. For each element, you can now bind to any property of the MyDataContext class, such as Title, or SubTitle.

For example... for a TextBox in the XAML, look in the Properties Window for the Text property. Click the dot beside the Text value, select "Data Binding...", go to the "Explicit Data Context" tab in the "Create Data Binding" dialog, and there I will find my MyDataContext class listed. I can expand it, and see the properites, then select the "Title" property. Done!

At run time, the code-behind of the XAML page can do something like:
public MyWindow() {
  InitializeComponent();
}
public MyDataContext SetDataContext {
  set { DataContext = value; }
}


Please note, the assignment of the DataContext does not need to be done in the constructor. Instead, a Presenter can be assigning an instance of MyDataContext at a later time.

C# Help Edit

Keywords

binding, databinding, intellisense, Expression Blend, ExpressionBlend, business objects

All content is Copyright ©2007 Xceed Software Inc. unless otherwise indicated. See the Terms of Service. Contributors must read and agree to the Contribution Policy. WPFwiki is brought to you by Xceed, makers of the powerful yet free Xceed DataGrid for WPF.