MVVM Binding - creating a control in a View, how bind to property in ViewModel?
We add tabcontrols to our application at runtime. Each tabcontrol is given a ViewModel as a DataContext. We add the tabcontrols by sending a message to the main app View; the message contains the ViewModel to be used as datacontext.
From the main app ViewModel, we add tabitems to the tab controls by sending a message to the main app view to create a TabItem and add it to the specified TabControl.
I'd like to bind certain properties of the TabI开发者_如何学Ctem to certain properties of the TabControl's ViewModel; this needs to be done programmaticaly, of course.
Since the tabcontrol and tabitem don't know about ViewModels (only DataContext), how do I specify the properties of the ViewModel to bind the tabitem properties too?
Thanks for any advice...
Messenger.Default.Register<AddTabControlMessage>(this, m =>
{
TabControl tc = new TabControl();
tc.DataContext = m.ViewModel;
// etc.
} );
You can cast the DataContext to the type of the ViewModel and then access the properties that way.
tc.SomeProperty = ((MyViewModel)DataContext).SomeVMProperty;
精彩评论