Programmatically Add Controls to WPF Form

前端 未结 3 1208
悲哀的现实
悲哀的现实 2021-01-31 04:02

I am trying to add controls to a UserControl dynamically (programatically). I get a generic List of objects from my Business Layer (retrieved from the database), and for each o

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-31 04:36

    I would listen to Charlie and Jobi's answers, but for the sake of answering the question directly... (How to add controls and manually position them.)

    Use a Canvas control, rather than a Grid. Canvases give the control an infinite amount of space, and allow you to position them manually. It uses attached properties to keep track of position. In code, it would look like so:

    var tb = new TextBox();
    myCanvas.Children.Add(tb);
    tb.Width = 100;
    Canvas.SetLeft(tb, 50);
    Canvas.SetTop(tb, 20);
    

    In XAML...

    
      
    
    

    You can also position them relative to the Right and Bottom edges. Specifying both a Top and Bottom will have the control resize vertically with the Canvas. Similarly for Left and Right.

提交回复
热议问题