In WPF, an event is displayed when any data context of the control changes. However, there is no similar function in Silverlight 4. We can achieve this by ourselves to meet our needs.
View code
1 Public Interface Idatacontextchangedhandler <t> Where T: frameworkelement 2 { 3 Void Ondatacontextchanged (T sender, dependencypropertychangedeventargs E ); 4 } 5 6 Public Static Class Datacontextchangedhelper <t> Where T: frameworkelement, idatacontextchangedhandler <t> 7 { 8 Public Static Readonly Dependencyproperty internaldatacontextproperty = 9 Dependencyproperty. Register (" Internaldatacontext " , 10 Typeof (Object ), Typeof (T ), New Propertymetadata (ondatacontextchanged )); 11 12 Public Static Void BIND (t control) 13 { 14 Control. setbinding (internaldatacontextproperty, New Binding ()); 15 } 16 17 Private Static Void Ondatacontextchanged ( Object Sender, dependencypropertychangedeventargs E) 18 { 19 T control = (T) sender; 20 Control. ondatacontextchanged (control, e ); 21 } 22 }
How to use:
Set binding in the constructor of the custom control.
View code
1Datacontextchangedhelper <silverlightdatagrid>. BIND (This);
It must be added that this feature is already provided in Silverlight 5.
View code
1 < Stackpanel Orientation = "Vertical" > 2 < ComboBox X: Name = "Lstroles" Selectionchanged = "Lstroles_selectionchanged" Width = "100" Height = "30" > 3 < Listboxitem > User </ Listboxitem > 4 < Listboxitem > Admin </ Listboxitem > 5 </ ComboBox > 6 7 < Stackpanel Orientation = "Vertical" X: Name = "Spdetails" Datacontextchanged = "Spdetails_datacontextchanged" > 8 < Stackpanel Orientation = "Horizontal" > 9 < Textblock Text = "Username :" > </ Textblock > 10 < Textblock Text =" {Binding username} " > </ Textblock > 11 </ Stackpanel > 12 < Stackpanel Orientation = "Horizontal" > 13 < Textblock Text = "Tasks count :" > </ Textblock > 14 < Textblock Text =" {Binding taskscount} " > </ Textblock > 15 </ Stackpanel > 16 </ Stackpanel > 17 </ Stackpanel >
Event handling in code behind:
View code
1 Private Void Lstroles_selectionchanged ( Object Sender, selectionchangedeventargs E) 2 { 3 Listboxitem objitem = lstroles. selectedvalue As Listboxitem; 4 If (Objitem. content. tostring () = " User " ) 5 { 6 Spdetails. datacontext = Objuservm; 7 } 8 Else 9 Spdetails. datacontext = Objadminvm; 10 } 11 12 Private Void Spdetails_datacontextchanged ( Object Sender, dependencypropertychangedeventargs E) 13 { 14 MessageBox. Show ( " Datacontext changed event " ); 15 }