views:

26

answers:

1

Simple case:

<usercontrol>
   <Views:UserListView x:Name="settingsTreeView"/>
   <Button DataContext="{Binding ElementName=settingsTreeView, Path=SelectedItem}"
           Command="{Binding CreateChildCommand}"/>
</usercontrol>

The task just is to bind to button a DataContext which implements CreateChildCommand. DataContext is the selected item in the treeview. Nothing to happen. I have checked the button properties at run time: both Command and DataContext properties of the button are null.

Questions:

  1. Is it valid to change DataContext at runtime?
  2. How to pass selected item to the Command object?

Concerning commanding in Silverlight you can refer to:

http://johnpapa.net/silverlight/5-simple-steps-to-commanding-in-silverlight/ http://community.infragistics.com/silverlight/media/p/125526.aspx

http://houseofbilz.com/archives/2009/05/22/adventures-in-mvvm-commands-in-silverlight/ http://www.silverlightshow.net/items/Silverlight-4-How-to-Command-Control.aspx

something goes wrong

+1  A: 

First thing to do would be to check if your bindings are failing. You should see some sort of output in the output log if this is the case. Its valid to change the DataContext at runtime, and you can bind the selected item to the CommandParameter property on the button if you want it to be passed to the command. Let me know if you have errors in your output log or not.

Graham Murray
Hello.There are no binding fails.I've tried to turn on the property change notification on SelectedItem property,and it worked out well. I've made the SelectedItem a dependency property.Although this is not the best decision in the current context. It would be better design without data context switch on changing a selected item.
Dmitry