简体   繁体   English

UserControl位置

[英]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. 我正在开发一个WPF应用程序,我已经创建了一个自定义用户控件,因为我需要在主窗口上创建它的实例。 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. 但是我需要按顺序放置每一个,所以,我如何设置每个的X和Y位置。 I've tried creating a method in my usercontrol to set the margin property, example: 我已经尝试在我的usercontrol中创建一个方法来设置margin属性,例如:

    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? 还有另一种方法吗?

When you add your control to a Grid container, you should set its position by setting Column and Row . 将控件添加到Grid容器时,应通过设置ColumnRow来设置其位置。

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. 为此,您需要将网格配置为具有添加新用户控件所需的行数和列数。

An often neglected control is the UniformGrid . UniformGrid是一个经常被忽视的控件。

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

Proceed to add the UserControl as you were before. 继续像以前一样添加UserControl

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属性。

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

I would make an ObservableCollection of the objects and place them inside a stack panel. 我会创建一个对象的ObservableCollection并将它们放在一个堆栈面板中。 That way you can add/remove/order the user controls. 这样您就可以添加/删除/订购用户控件。 Then you could just do the set up the size inside of the stacks. 然后你可以设置堆栈内部的大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM