Search code examples
c#wpfwpf-controlscode-behind

Create multiple instances of the same control with different visual properties via code-behind in WPF


I am trying to prototype a GUI and created a minimal WPF project using Expression Blend 4.

I have a main window (XAML+codebehind) with eight instances of an UserControl, which is defined separately (XAML+codebehind). This user control has some containers and shapes, and I would like to have each of its instances in the main window to have a different appearance.

The idea would be to expose some properties of this control, and treat them as parameters. Then, I could use code behind to populate the main window, and for each instance I could add some hardcoded parametrizations. For example in pseudo-code:

first = new mycontrol;
mainwindow.maincontanier.add(first);
first.leftpanel.width = 100;
first.rightpanel.background = Gray;

second = new mycontrol;
mainwindow.maincontainer.add(second);
second.leftpanel.smalldot.stroke = Red;
second.leftpanel.insideborder.thickness = 2;

etc.

The problem is: I have no idea how this is usually done, so I appreciate any suggestion, specially in the form of minimally working code blocks.

Just to remember, I am doing this only as a design study, so I can compare different possible visual states of the control. I am not a C# programmer, and there is not any other GUI functionality involved.


Solution

  • If you are asking how to add items programatically:

    //get mainwindow
    Window main = App.Current.MainWindow;
    myControl c1 = new myControl();
    //change properties
    myControl c2 = new myControl();
    //change properties
    
    //choose a container you want
    StackPanel s = new StackPanel();
    
    //add objects to container
    s.Children.Add(c1);
    s.Children.Add(c2);
    
    //make container as your main content
    main.Content = s;