July 23, 2010

Strange things about silverlight data binding

Filed under: Uncategorized — alexezh @ 5:34 pm

There are number of samples about Silverlight databinding on the web mostly based on the standard sample. When you try to diverge from the sample you might hit issues. Couple things which I found while playing with SL:

1. Property for data binding have to be defined with setter and getter; for example

class Customer {
public String Name { get; set; }

2. Setters are not called during binding. If you want to know when property is set, you have to handle this in notification for dependency property

3. Binding of complex objects across child objects is hard :). Here is an example. Data contains of two classes Bar and Foo

class Bar {
public String Name1 { get; set; }

class Foo {
public String Name2 { get; set; }
public Bar Child;

I would like to bind Foo object to the parent control and pass Bar to the child control. It works by itself but fails when I try to bind Name1 in the child control. The reason seems to be following. In order for child control to perform data binding of Name1 we have to set DataContex for Bar object. But the DataContex has already been set by binding performed of the parent control. There is an article on about proxy binding which might help. The simpler option seems to be to avoid binding for Foo.Child in the parent object and just set DataContext manually.

Blog at WordPress.com.