I know that's bad design, but I need access to the view from my viewmodel. This is because I have some old controls, e.g. Winforms controls, that don't support binding and need to be filled by code.
I'm using the MVVM model of AvalonDock 2.0 and have something similar to this:
<ad:DockingManager x:Name="dockManager"
DocumentsSource="{Binding Files}"
AnchorablesSource="{Binding Tools}"
ActiveContent="{Binding ActiveDocument, Mode=TwoWay, Converter={StaticResource ActiveDocumentConverter}}">
<ad:DockingManager.LayoutItemTemplateSelector>
<local:PanesTemplateSelector>
<local:PanesTemplateSelector.NavigationViewTemplate>
<DataTemplate>
<tvext:TreeViewExtended />
</DataTemplate>
</local:PanesTemplateSelector.NavigationViewTemplate>
</local:PanesTemplateSelector>
</ad:DockingManager.LayoutItemTemplateSelector>
So the template NavigationViewTemplate is bound to one item of the collection Tools, which is my ViewModel of type NavigationViewModel.
I have no problem binding e.g. a TextBox to a property of my viewmodel. But I don't know how I can get access from my NavigationViewModel to the tvext:TreeViewExtended control inside the template in order to fill it.
TIA Michael
create Events in your viewmodel and just subscribe to these events in your view, so view and viewmodel are still not strong coupled and you get what you want.
yeah, I am not a big fan of letting the ViewModel know about the view, but since you asked, here's one idea:
I suggest that you do not access the Winforms control from your ViewModel. Keep everything that relates to the view in the view. You can do this as follows:
Create a WPF custom control, e.g. named
TreeViewExtendedWrapper
. (See this article for a short tutorial how to create custom WPF controls).Inside the control template of the custom control (in the Themes\Generic.xaml file), place your Winforms control:
Add dependency properties to your custom control for all Winforms control properties that you need to bind to the ViewModel.
Also add dependency properties to your custom control for all commands that you need to bind to the view model.
Write C# code inside the code-behind of the custom control to connect the dependency properties of your custom control to the properties, events, and methods of the Winforms control.
Inside your data template, place your custom control with any necessary data bindings:
With this approach, you can use data binding to connect ViewModel and Winforms control, i.e. you do not violate MVVM principles.