I have a Page that has three child UserControls. I set the DataContext viewmodel resource in the parent Page and the three child controls reference the parents DataContext because all 3 child user controls use the same ViewModel. All good.
However, one of the UserControls is having binding problems (I can see this because of the new XAML debugging feature in Silverlight 5 Beta.) The UserControl in question is an ItemsControl. Inside each Item is a button and 2 text boxes. That button is bound to a Command. The error is that the Button cannot find its binding. The 2 textboxes are binding correctly. The ItemSource of the开发者_C百科 ItemsControl is bound to a ObservableCollection in the viewmodel.
My Question is this: How can I tell the Button to look for its binding "at a higher level" than the Observable Collection ie: Go to the view model, not your direct parent (the Observable Collection). You can't set the DataContext
for the button in the ChildControl
because the reference to the view model isnt there. It's in the parent.
Try this:-
Give your ItemsControl a name. In your button binding include ElementName=NameOfItemsControl
, prefix the path of the binding with DataContext.
.
You should be able to use RelativeSource binding to get to your viewmodel
{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}},
Path=DataContext.MyButtonCommand}
I have since moved all my SL5 projects back to SL4. The new XAML debugging feature of SL5 worked for no more than a few days and is now permanently crippled throwing errors about not being able to find PDBs. I would advise anyone developing large projects to stay away from SL5 until its tested and proven or else you will end up wasting huge amounts of time trying to analyse the bizarre errors that SL5 produces.
精彩评论