65.9K
CodeProject is changing. Read more.
Home

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

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.33/5 (2 votes)

Jun 4, 2010

CPOL
viewsIcon

9660

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…

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.