开发者

Displaying UserControls based on the type a TreeView selection is bound to

开发者 https://www.devze.com 2022-12-26 16:09 出处:网络
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 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:

  • setting up the TreeView with one HierarchialDataTemplate per type
  • adding all the UserControls to the right pane, but collapsed
  • implementing SelectedItemChanged on the TreeView, and se开发者_如何学Gotting the appropriate usercontrol to visible and the others to collapsed.

    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.

  • 0

    精彩评论

    暂无评论...
    验证码 换一张
    取 消

    关注公众号