TheChaseMan's Frenetic SoapBox

Always looking for better ways to do things...

More WinFX Fun: DataBinding with "Avalon"

For my databinding example, I construct my XAML markup using a single column GridPanel for my layout. The GridPanel contains a button that gets wired up to a Click event handler in the code-behind. My ListBox will get bound to a generic collection of Person objects within the button's click event handler. The Style defined under <Window.Resources> is used to tell the listbox how to display each Person object. Otherwise it would just display "GridBindApp.Person" instead of the actual properties (Name and Age). This is a result of the databinding operation using the ToString() method on the Person object. Clearly, that's not what I want to do, so the  Style gives me control over how the ListBox object binding display end up looking.

 

 

<Window x:Class="GridBindApp.Window1" xmlns="http://schemas.microsoft.com/2003/xaml" xmlns:x="Definition" Text="GridBindApp">
   
<Window.Resources>
        <
Style x:Name="PersonStyle">
            <
Style.VisualTree>
                <
FlowPanel>
   
                <Text TextContent="*Bind(Path=Name)" />
                    <Text TextContent=":" />
                    <Text TextContent="*Bind(Path=Age)" />
                </FlowPanel>
            </Style.VisualTree>
        </Style>
    </Window.Resources>

    <GridPanel Columns="1" DockPanel.Dock="Left">
        <Button ID="buttonBind" Content="Bind" Click="buttonBind_Click" Width="100"></Button>
        <ListBox ItemStyle="{PersonStyle}" ItemsSource="*Bind()" />
    </GridPanel>
</Window>

 

My code-behind is very straight-foward. There is a definition for a Person class, followed by a partial class definition for my app window where is buttonBind_Click defined. The buttonBind_Click event handler creates a generic collection of type Person and sets the DataContext property. That's it!

 

namespace GridBindApp

{

    public class Person

    {

        string _name;

        int _age;

 

        public string Name

        {

            get { return this._name; }

            set { this._name = value; }

        }

 

        public int Age

        {

            get { return this._age; }

            set { this._age = value; }

        }

 

        public Person(string name, int age)

        {

            this._name = name;

            this._age = age;

        }

    }

 

    public partial class Window1 : Window

    {

        private void buttonBind_Click(object sender, EventArgs e)

        {

            ICollection<Person> people = new Collection<Person>();

                people.Add(new Person("Sean", 32));

            people.Add(new Person("Geo", 26));

            people.Add(new Person("Brittany", 2));

            this.DataContext = people;

        }

    }

}

Digg!

posted on Sunday, November 28, 2004 3:36 PM

Feedback

No comments posted yet.