topograph topograph - 15 days ago 6
C# Question

WPF C#: How to add a usercontrol to a thumb control programatically?

another day, another question :) :
At the moment in my XAML i have a thumb on a canvas which contains a usercontrol:

<Canvas Name="SweetCanvas">
<Thumb Name="tmbThumb" Canvas.Left="245" Canvas.Top="185" DragDelta="Thumb_DragDelta">
<Thumb.Template>
<ControlTemplate>
<my:UserControl1 />
</ControlTemplate>
</Thumb.Template>
</Thumb>
</Canvas>


which works. But i want to add a thumb like this programatically, so i tried this:

UserControl1 newUC= new UserControl1 (); //UserControl i want on the thumb
Thumb tmbDragThumb = new Thumb()
tmbDragThumb.DragDelta += new DragDeltaEventHandler(Thumb_DragDelta); //event for the thumb
//Dont really know what to do here :/
tmbDragThumb.Template = newUC; //Adding usercontrol to something something something?

SweetCanvas.Children.Add(tmbDragThumb); //add the final Thumb to Canvas


I don't really know how to add content to this thumb, like i did in the XAML

Answer

just found a solution by myself using the FrameworkElementFactory:

Thumb tmbDragThumb = new Thumb();
tmbDragThumb.DragDelta += new DragDeltaEventHandler(Thumb_DragDelta);
ControlTemplate template = new ControlTemplate();
var fec= new FrameworkElementFactory(typeof(UserControl1 ));
template.VisualTree = fec;
tmbDragThumb.Template = template;

SweetCanvas.Children.Add(tmbDragThumb);

this was helpful: https://code.msdn.microsoft.com/windowsdesktop/WPF-Styles-and-Control-b6732c24