Search code examples
wpfuser-controlscontroltemplatecomposite

WPF Howto create a reusable composite component with configurable content?


I would like to create a component that is made up of an arbitrary control and a little button beside this control (same as in this example: http://putridparrot.com/blog/wpf-composite-control/).

My problem is that the content element (the one beside the button) does not always have to be a TextBox, it can be any kind of control. Is there a way to create a component that provides the button, and for which the content element can be freely chosen at design- or even run-time?


Solution

  • You can replace the textbox by a stackpanel, and then in code behind add the children with the controls you want.

    ex: In the XAML:

    <stackpanel name="testPanel" Grid.Column="0" />
    

    In code behing when the usercontrol or window is loaded or when a button is pressed..put this:

    testPanel.Children.Add(new Combobox()); --- something like this...
    

    This way, you can assure that whatever you put in the stackpanel (it can be another grid or a dockpanel...) will appear before the button and that you can on runtime create the control you need.

    regards,

    SM