WPF Binding Treeview element to a UserControl
I have a tree view that is using the Model V开发者_如何学Ciew architecture, each TreeViewItem has a windows Form attribute, when I click on a node I want the application to display the form associated with that node to the right hand side of the tree.
How can you achieve this using binding I have tried the following but the user control Associated with ApplicationForms doesn't get displayed.
<ContentControl Margin="163,5,127,5" Content="{Binding SelectedItem,ElementName=ApplicationTree}">
<ContentControl.Resources>
<DataTemplate DataType="{x:Type local:ApplicationViewModel}">
<StackPanel>
<TextBlock Text="Displaying an A!" />
<ContentPresenter Name="MyContent">
<ContentPresenter.Content>
<UserControl x:Name="UserCntrl2" HorizontalAlignment="Stretch" Height="Auto" Width="Auto" Content="{Binding ApplicationForms}"/>
</ContentPresenter.Content>
</ContentPresenter>
</StackPanel>
</DataTemplate>
<DataTemplate DataType="{x:Type local:ApplicationsViewModel}">
<StackPanel>
<TextBlock Text="Displaying a B!" />
<!--<TextBlock Text="{Binding Bar}" />-->
</StackPanel>
</DataTemplate>
</ContentControl.Resources>
</ContentControl>
Since you're using MVVM, you can alternativly put that kind of logic in the view model. you can then bind the IsSelected property of tree node to your viewmodel, then when IsSelected get set to true by wpf (when the use selects the item) you can do whatever you want.
Its a very useful pattern to use view models this way. your viewmodels can have references to all kinds of stuff and affect them based on selection or expansion. You can also go the other way around and have code affect the viewmodels and let the databinding update the actual controls
Here is a pretty good article on MVVM and treeview
You should also check out the HierarchicalDataTemplate if you're working with treeviews
-edit-
After reading the question properly, i see that you're already doing the right thing, that is binding your master control to the SelectedItem of the Treeview. I do belive the SelectedItem property points to the TreeViewItem though, not the actual VM. Perhaps thats the problem?
精彩评论