Tip/Trick: Creating and Using Silverlight and WPF User Controls
page 3 of 5
by Scott Guthrie
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 23343/ 49

Data Binding Address Objects to our AddressUserControl

Now that we have some user controls that encapsulate our Address UI, let's create an Address data model class that we can use to bind them against.  We'll define the class like below (taking advantage of the new automatic properties language feature):

Within the code-behind file of our Page.xaml file we can then instantiate two instances of our Address object - one for the shipping address and one for the billing address (for the purposes of this sample we'll populate them with dummy data).  We'll then programmatically bind the Address objects to our AddressUserControls on the page.  We'll do that by setting the "DataContext" property on each user control to the appropriate shipping or billing address data model instance:

Our last step will be to declaratively add {Binding} statements within our AddressUserControl.xaml file that will setup two-way databinding relationships between the "Text" properties of the TextBox controls within the user control and the properties on the Address data model object that we attached to the user control:

When we press F5 to run the application we'll now get automatic data-binding of the Address data model objects with our AddressUserControls:

Because we setup the {Binding} declarations to be "Mode=TwoWay", changes users make in the textboxes will automatically get pushed back to the Address data model objects (no code required for this to happen). 

For example, we could change our original shipping address in the browser to instead go to Disneyland:

If we wire-up a debugger breakpoint on the "Click" event handler of the "Save" button (and then click the button), we can see how the above TextBox changes are automatically reflected in our "_shippingAddress" data model object:

We could then implement the SaveBtn_Click event handler to persist the Shipping and Billing Address data model objects however we want - without ever having to manually retrieve or manipulate anything in the UI controls on the page.

This clean view/model separation that WPF and Silverlight supports makes it easy to later change the UI of the address user controls without having to update any of our code in the page.  It also makes it possible to more easily unit test the functionality (read my last post to learn more about Silverlight Unit Testing).


View Entire Article

User Comments

No comments posted yet.






Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-03-29 3:41:40 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search