Thursday 4 August 2011

Customizing the Silverlight 4 DataForm

I’ve been working on a web based project in my spare time, and was trying to edit an object downloaded from my web server.

In the end, I eventually found that the DataForm from the Silverlight toolkit should make it easy to display the data in my object.  So, Initially, I let it wire up to my object like this:

<toolkit:DataForm Grid.Column="1"          
Name="dataForm1" ItemsSource="{Binding Gigs}"
CurrentItem="{Binding ElementName=dataGridGigs,
Path=SelectedItem, Mode=TwoWay}"
/>




 

Unfortunately, the Gigs object had a member declared like this:

 

public DateTime StartTime { get; set; }


which generated a default field editor of a date picker, which didn’t allow me to set the time!  Unfortunately, the time is just as important as the date in my application.


I searched around the web for awhile to find out how to customize the DataForm, but unfortunately most of the references were for Silverlight 3, and there have been many breaking changes since then.


So, I dug out my copy of Silverlight 4 unleashed and found the Section in Chapter 8, on page 212 that specifies how to define the fields manually.  Alas, the description warns off the user, saying that the validation summary won’t appear.


Sure enough, the code included didn’t show the validation summary as advertised.


Nevertheless, I persisted.


<toolkit:DataForm Grid.Column="1"  
Name="dataForm1" AutoGenerateFields="False"
ItemsSource="{Binding Gigs}"
CurrentItem="{Binding ElementName=dataGridGigs,
Path=SelectedItem, Mode=TwoWay}"
>
<toolkit:DataForm.EditTemplate>
<DataTemplate>
<StackPanel>
<!-- ... -->
<toolkit:DataField Label="StartTime">
<TextBox Text="{Binding Path=StartTime,

Mode=TwoWay}"
/>
</toolkit:DataField>
</StackPanel>
</DataTemplate>
</toolkit:DataForm.EditTemplate>
</toolkit:DataForm>




Suddenly, not only did validation appear, but my data was also updated in the object.


The key is setting the TextBox databinding to be TwoWay!

No comments:

Post a Comment