BlackCath
BlackCath

Reputation: 826

UserControl Position

I'm developing a WPF application, and I have created a custom usercontrol because I need to create instances of it, on the main window. So, this is how I create a new instance:

        var MyCard = new vCard();
        MainGrid.Children.Add(MyCard);
        Grid.SetColumn(MyCard, 1);
        Grid.SetRow(MyCard, 0);

But I need to place every one in order, so, how can I set the X & Y position of each one. I've tried creating a method in my usercontrol to set the margin property, example:

    public void SetX(double X)
    {
        double  Y =this.Margin.Top;            
        this.Margin = new Thickness(X, Y, 0, 0);            
    }

But, it's not working. Is there another way to do it?

Upvotes: 3

Views: 1599

Answers (3)

Nelson Reis
Nelson Reis

Reputation: 4810

When you add your control to a Grid container, you should set its position by setting Column and Row.

In order to do that, you will want to configure your grid to have the number of rows and columns necessary for adding your new user controls.

Upvotes: 3

rreeves
rreeves

Reputation: 2458

I would make an ObservableCollection of the objects and place them inside a stack panel. That way you can add/remove/order the user controls. Then you could just do the set up the size inside of the stacks.

Upvotes: 1

Aaron McIver
Aaron McIver

Reputation: 24713

An often neglected control is the UniformGrid.

<UniformGrid Name="MainGrid" Rows="3" Columns="2"/>

Proceed to add the UserControl as you were before.

var MyCard = new vCard();
MainGrid.Children.Add(MyCard);

This will provide a nice and evenly distributed container for your items. If you want to adjust the spacing between items there are couple ways to do it, with the easiest being the adjustment of the Margin property on your UserControl itself.

<UserControl Margin="8" ... />

Upvotes: 2

Related Questions