简体   繁体   中英

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. Then you manipulate the members of the observablecollection and the itemscontrol will create the corresponding controls for you according to its itemtemplate property.

<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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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