Click here to Skip to main content
15,888,610 members
Articles / Programming Languages / C#

A DataForm with a Little Configuration (Or is it Convention)?

Rate me:
Please Sign up or sign in to vote.
4.33/5 (2 votes)
4 Jun 2010CPOL 9.6K   1  
A DataForm with a little configuration (or is it convention)?

I absolutely love the DataForm (I even ported the Silverlight version to WPF). One of the common questions I occasionally receive is how to express a relationship. Have a look at the following 3 data tables:

The Products table has a Category and Tax that needs to be looked up… How do I do this using a DataForm?

The DataForm fires an event for every property that it auto-generates a field for…

C#
private void DataFormAutoGeneratingField
	(object sender, DataFormAutoGeneratingFieldEventArgs e)
{
    if (e.PropertyName != "Id")
    {
        if (e.PropertyName.EndsWith("Id"))
        {
            dynamic collector = _collectors[e.PropertyName];

            var comboBox = new ComboBox
                                {
                                    Margin = new Thickness(0, 3, 0, 3),
                                    DisplayMemberPath = "Name",
                                    ItemsSource = collector.Collect(),
                                    SelectedValuePath = "Id"
                                };

            var binding = new Binding(e.PropertyName)
                                {
                                    Source = df.CurrentItem,
                                    Mode = BindingMode.TwoWay,
                                    ValidatesOnExceptions = true,
                                    UpdateSourceTrigger =
					UpdateSourceTrigger.PropertyChanged
                                };

            comboBox.SetBinding(Selector.SelectedValueProperty, binding);

            e.Field.Label = e.PropertyName.Remove(e.PropertyName.Length - 2, 2);
            e.Field.Content = comboBox;
        }
    }
    else
    {
        e.Cancel = true;
        return;
    }
}

Now I just need to use a little convention! I basically check if the property ends with <Table>Id. If this is true, I assume that the first part is the table that I have to look up against. I then use my data access layer to fetch all the records from that table and populate my ComboBox!

And that is it!!! Easy, isn’t it?

For an example of this in action, check out the source of OpenPOS.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
South Africa South Africa
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --