Floating FB sharing byReview Results

Floating FB sharing byReview Results

  • WPF Tutorial

    • # Read in Your Language


    DataBinding in WPF

    Tutorial Home | DataContext | DataTemplate

    DataContext in WPF

    DataContext:


    Before we can go much further, we should talk about the DataContext property.

    The data context is much like Windows Forms’ DataSource property – it can represent an object or a list of objects for use in databinding. In “Avalon”, DataContext has a twist: the DataContext is inherited to all child elements – setting the DataContext on “Window” means that all the buttons and labels and listboxes can automatically look at the same source of data. A DataContext can be set on any FrameworkElement or FrameworkContentElement, which will trump the DataContext set on the parent element.

    Kinds of data sources


    “WPF” can databind to:

    Any CLR object - One can bind to properties, sub properties as well as indexers on a CLR object. The binding looks for properties etc using
    • Reflection - uses reflection and propertyInfo to get values of properties
    • CustomTypeDescriptor - If the object implements ICustomTypeDescriptor, the bindings uses this interface to get the values for the properties. This is useful, when the object does not have a static set of properties, but the properties are determined dynamically.

    In order for the data to “refresh” when the property changes, the CLR object should consider implementing INotifyPropertyChanged (preferred) or adding a matching event for the property: e.g. for a public string Foo { get; set; } create a public event EventHandler FooChanged;

    XmlNode – it is possible to databind to a fragment of XML (XML data island) or an entire XML file using the XmlDataProvider.
    ADO.Net Data Table – it is possible bind to fields on the Row of a DataTable as well as walk relationships in an ADO.Net DataSet from one table to another. This is done using the ICustomTypeDescriptor implementation on DataView.

    Dependency Object – it is possible bind to DependencyPropererties on other DependencyObjects.
    Specifying sources of data in {Binding}
    The DataContext can be used as the default source of data, that is if an element, or an element’s parent has a DataContext assigned, then the Binding object just picks that up as the object to bind against.

    If you want to bind to something other than what’s currently stuffed in the DataContext, you can set the data source explicitly. This is called an Explicit Data Source, because you’re not using the inherited stuff from the DataContext.

    Source:

    Explicitly sets the object to databind to, trumping what’s already been inhertited from the DataContext.
    ElementName:

    Useful for binding the property on one element to another.

    
                E.g. Binding textBox1.Text to button1.Content.
                    <TextBox Name="textBox1"/>
                    <Button 
                    Content="{Binding ElementName=textBox1, Path=Text}"/>
             

    RelativeSource:

    Useful for databinding in a ControlTemplate or a Style

    Fishing out the part of the data you actually want to use
    Obviously if a listbox and a label are pointing at the same object for their data, they’ll want to display different things. There are several ways to fish out the exact data you want.


    The rules for specifying “Path=” in a Binding markup extension

    Here’s a breakdown of the rules for parsing PropertyPath syntax from MSDN:

    Use it for specifying the property to bind to
    • This is the simplest case, “{Binding Path=Title}”
    Use it for specifying a subproperty
    • To get the length of the Title string in C#, you would int length = book.Title.Length. That’s “{Binding Path=Title.Length}”
    Use it to access one element in a list
    • To always databind to the title of the first book in the list of books, {Binding Path=[0].Title}


    Sample: Setting the DataContext in code
    Lets add two books to a list and show how to set up the DataContext.

    
                    <Window x:Class="WindowsApplication14.Window1"
                xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                Title="WindowsApplication14"
                Loaded="OnWindowLoaded"
                >
              <DockPanel>
                <TextBox DockPanel.Dock="Top" 
             Text="{Binding Path=Author}"/>
                <ListBox ItemsSource="{Binding}" 
                         IsSynchronizedWithCurrentItem="True"/>
              </DockPanel>
            </Window>
             

    
                public partial class Window1 : Window {
                    // Window1.xaml.cs
                    private void OnWindowLoaded(object sender, EventArgs e) {
                        List<Book> books = new List<Book>();
                        books.Add(new Book("Steinbeck", "Grapes of Wrath"));
                        books.Add(new Book("Twain", "Huckleberry Finn"));
                        
                        this.DataContext = books;
                    }
                }
                

    …sets up the object for all the child elements of the window to databind to – in our case, this is a list of books.

    
                <TextBox Text="{Binding Path=Author}"/>
                

    Since we did not specify Source, ElementName, or RelativeSource, the TextBox will look for a DataContext that is set somewhere either on itself or on one of its parents. It will access the “Author” property of the currently selected Book in the list of books.

    
                <ListBox ItemsSource="{Binding}" 
                         IsSynchronizedWithCurrentItem="True"/>
            

    The ItemsSource property specifies the place to populate the listbox items from. Because we have again not specified Source, ElementName, or RelativeSource, the listbox will go looking for a set DataContext.

    IsSynchronizedWithCurrentItem is a way of saying that as the listbox selection changes, change the current item that the binding is looking at and vice-versa. So when we keyboard through the books in the listbox, the author in the textbox changes.

    Data Binding: Sharing with DataContext

    
            <StackPanel DataContext=”{StaticResource photos}”>
            <Label x:Name=”numItemsLabel”
            Content=”{Binding Path=Count}” …/>
            …
            <ListBox x:Name=”pictureBox” DisplayMemberPath=”Name”
            ItemsSource=”{Binding}” …>
            …
            </ListBox>
            …
            </StackPanel>
            

    << Previous Topic >> | << Next >>