简体   繁体   English

如何以编程方式添加用户控件

[英]How to add user controls programmatically

I am trying to programmatically add a UserControl every time a button is clicked. 我试图每次单击按钮时以编程方式添加UserControl。 The first time it works but after that I can see the number of controls increasing but not being displayed. 第一次运行,但此后我看到控件的数量增加了,但没有显示。

private void AddRecord()
    {
        StackPanel wrp = (this.Content as Grid).Children[0] as StackPanel;
        wrp.Children.Clear();
        for (int i = 0; i < m_viewModel.RecordTimeConfig.Count; i++)
        {
            wrp.Children.Add(m_viewModel.RecordTimeConfig[i]);
        } 
    }

Every time I click the button m_viewModel.RecordTimeConfig is increased. 每次单击按钮m_viewModel.RecordTimeConfig都会增加。 The stackpanel has no set height and width. 堆栈面板没有设置高度和宽度。

this is your problem 这是你的问题

wrp.Children.Clear();

You're removing all the controls in your stack panel each time you press the key, so you are adding a new control but you are also removing the one that's already there. 每次按下该键时,都将删除堆栈面板中的所有控件,因此,您将添加一个新控件,但同时还将删除已经存在的控件。

I've found the problem. 我发现了问题。

It was due to the size of the user control it was larger than the size of the window. 这是由于用户控件的大小大于窗口的大小。

Thank you all for your help 谢谢大家的帮助

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

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