topograph topograph - 1 year ago 228
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">
<my:UserControl1 />

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 Source

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;


this was helpful:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download