简体   繁体   English

如何以适当的方式添加动态控件?

[英]How to add dynamic controls in proper way?

I have following code: 我有以下代码:

        for (int i = 0; i < 4; i++)
        {

            TextBlock Tb = new TextBlock();
            Tb.Text = k[3+i];
            Tb.Width = 205*((i<2)?1:0.5);
            Tb.Height = (stala*10)/3;
            Tb.Margin = margin;
            margin.Top += ((stala * 10) / 3);
            this.Str1.Children.Add(Tb);

        }

Textblocks are added but just for a second... when the animation stops, controls also dissapearing... Can anyone tell me why? 添加了文本块,但是只是一秒钟...当动画停止时,控件也消失了...有人可以告诉我为什么吗?

No, if you need a set of repeating controls at runtime that are of unknown quantity at designtime, the correct way is to use an itemscontrol or some control that inherits from itemscontrol like gridview and bind that itemscontrol to a property of value observablecollection. 不,如果您需要在运行时使用一组重复的控件,而这些控件在设计时数量未知,则正确的方法是使用itemscontrol或某些控件(这些控件继承自gridview之类的itemscontrol并将该控件绑定到value Observablecollection的属性上)。 Then you manipulate the members of the observablecollection and the itemscontrol will create the corresponding controls for you according to its itemtemplate property. 然后,您操纵observablecollection的成员,itemscontrol将根据其itemtemplate属性为您创建相应的控件。

<ItemsControl ItemsSource="{Binding}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel>
                <StackPanel.ChildrenTransitions>
                    <AddDeleteThemeTransition />
                </StackPanel.ChildrenTransitions>
            </StackPanel>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <TextBox Text="{Binding}" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

In addition, if you want animations, then on the itemscontrol's itemspanel you can set the childrentransitions with something from the animation library and you are good to go. 另外,如果您想要动画,则可以在itemscontrol的itemspanel上使用动画库中的某些内容设置childrentransitions,这是您的最佳选择。

It sounds like binding may be new to you. 听起来绑定对您来说可能是新的。 You might want to review my primer on the topic here: http://blog.jerrynixon.com/2012/10/xaml-binding-basics-101.html 您可能需要在这里查看有关该主题的入门知识: http : //blog.jerrynixon.com/2012/10/xaml-binding-basics-101.html

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

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