I am making an app in WPF in a style similar to Windows Explorer, with a TreeView on the left and a pane on the right.
I want the contents of the right pane to change depending on the type of the selected element in the TreeView.
For example, say the top level in the Tree View contains objects of class "A", and if you expand the "A" object you'll see a list of "B" objects as children of the "A" object.
If the "A" object is selected, I want the right pane to show a user control for "A", and if "B" is selected I want the right pane to show a user control for "B".
I've currently got this working by:
However, I'm sure there's a better/more elegant way to switch out the views based on the type the selection is bound to, perhaps by making more use of data binding... any ideas?
Have you considered displaying a ContentControl as the right-side pane, and using DataTemplates to customize the contents? Then you could simply bind the right pane to the selected item of the TreeView.
For example:
<ContentControl Content="{Binding SelectedItem,ElementName=treeView1}">
<ContentControl.Resources>
<DataTemplate DataType="{x:Type my:A}">
<StackPanel>
<TextBlock Text="Displaying an A!" />
<TextBlock Text="{Binding Foo}" />
</StackPanel>
</DataTemplate>
<DataTemplate DataType="{x:Type my:B}">
<StackPanel>
<TextBlock Text="Displaying a B!" />
<TextBlock Text="{Binding Bar}" />
</StackPanel>
</DataTemplate>
</ContentControl.Resources>
</ContentControl>
You can use the ContentPresenter class with a DataTemplateSelector. Bind the Content property to the TreeView.SelectedItem property then use the DataTemplateSelector to conditionally choose the template.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With