(First post on these forums!)


I have a problem which I cannot figure out myself.
I am trying to create a new FrameworkElement/Control (e.g. Button) and add it to a Grid via code behind. The problem is I need a function that can do this generically with any element.
For example, if I know that input element is of type Button, I can simply do something like:

//Create and configure button
Button myButton = new Button();
myButton.Margin = new Thickness(xValue, yValue, 0, 0);
myButton.Height = fe.Height;
myButton.Width = fe.Width;
Grid subGrid = new Grid();
TextBlock myTextBlock = new TextBlock();
myTextBlock.Text = "My Button";
myButton.Content = subGrid;
//Add it to the grid

My problem is that I need to be able to do this for any element (e.g. Scrool bar, Canvas, Rectangle, Grid etc etc). I could detect which type of element it is and then call the according method (have a different method for each element type), but this would be messy. There must be a better way, right?

Tl;dr I need to create generic elements of a given type and add them to a grid. Any help appriciated!

Thanks in advance!