Search code examples
wpfpanelitemscontrol

How to make an ItemsControl that has only the special type?


My English skills are poor because I'm not a native English speaker. I hope that you can understand.

I would like to construct a control that can receive only a special type. I am thinking of constructing it deriving ItemsControl. First, I tried to construct it deriving Panel but I thought that the way is unsuitable at this subject so I tried to use the ItemControl.

Anyway, here my problem is the ItemCollection of the ItemsControl can has all types but I want the control I try to construct to have only a special type.

For example, The construction of the code I expect is as follows. (The name of the control that I'm trying to construct assumed "DockManager".) (The name of the special type that "DockManager" can have, assumed "DockLayout" and "DocumentLayout".)

A successful example.

<DockManager>
    <DockLayout Header="example" Content="{Binding}" DockManager.Dock="Top"/>
    <DockLayout Header="example2" Content="{Binding}" DockManager.Dock="Bottom"/>
    <DocumentLayout Header="example2" Content="{Binding}"/>
</DockManager>

Example of failure

<DockManager>
    <Grid/>      <-- Error : DockManager can't has the Grid control.
    <TextBox/>   <-- Error : DockManager can't has the TextBox control.
</DockManager>

Could I reach the above goal in the base on ItemsControl? I am not willing to cling to ItemsControl. If you have a better way that can reach the above goal, could you teach me the way?

Thank you for reading.


Solution

  • Could I reach the above goal in the base on ItemsControl?

    Short answer: No.

    An ItemsControl has an ItemsSource property that can be set to any IEnumerable and you can't change this API by creating a new class that derives from it.

    So if you want a control that only works with a spcific type of items, you will have to create your own custom control from scratch basically. You may take a look at the source code of the ItemsControl and proceed from that.