adontz
adontz

Reputation: 1438

WPF binding producing various controls

I'm newbie to WPF, and maybe ask some stupid question. However.

I have a tree of my custom class (WidgetDescriptor) derivied classes (MenuDescriptor, LabelDescriptor, ButtonDescriptor, SelectDescriptor). Derived classes provide type-specific properties (SelectDescriptor describes drop-down list and has property, Items, while ButtonDescriptor has properties Text and Image).

WidgetDescriptor has a property Children which is observable collection of WidgetDescriptor instances.

So, application main menu is a tree of MenuDescriptor instances with ButtonDescriptor instances as leaves. Toolbar may contain SelectDescriptor (drop-down box), etc.

I want to know is it possible to map WPF controls to descriptor types with binding? I want WPF to check WidgetDescriptor derived class type and create specific control? And of these hierarchically, of course.

Upvotes: 2

Views: 65

Answers (1)

brunnerh
brunnerh

Reputation: 185445

There is some built-in functionality for this, every DataTemplate has a DataType, if this is set to the type of your object and the DataTemplate is placed in a Resources dictionary without key it will automatically be used if an object of that type is encoutered in the datasource.

For your menu you hence can just create a bunch of templates:

<Menu ItemsSource="{Binding RootList}">
    <Menu.Resources>
        <HierarchicalDataTemplate DataType="{x:Type obj:MenuDescriptor}"
                ItemsSource="{Binding Children}">
            <!-- ... -->
        </HierarchicalDataTemplate>
        <DataTemplate DataType="{x:Type obj:ButtonDescriptor}">
            <!-- ... -->
        </DataTemplate>
        <!-- ... -->
    </Menu.Resources>
</Menu>

Use hierarhical ones for trees, they provide an internal ItemsSource for children of the item. It seems redundant to me to have more than one class for a menu tree though, leaves can just be MenuDescriptors as well, albeit without any children (as is the case with normal MenuItems).

Upvotes: 1

Related Questions