开发者

How to change the user control in WPF?

I'm creating something like a wizard, and I'm u开发者_运维知识库sing several User Control, but the roblem is I need to get the parent from that element to replace for the next user control.

How can I do that?


Lets think you have 5 UserControls. While creating wizard you need to add new UserControl inside a grid and remove the previous UserControl from the same parent grid.

The following function will automatically remove the older UserControl and add the new UserControl.. But for the first UserControl you can directly add it to its parent using MyParentPanel.Children.Add(myFirstUserControl);

       private void AddNewUserControlAndAutoRemoveOldUserControl(UserControl control)
        {
            if (control != null)
            {
                Panel parent = control.Parent as Panel;

                if (parent != null)
                {
                    // Removing old UserControl if present
                    if(parent.Children.Count > 0)
                        parent.Children.RemoveAt(0);

                    parent.Children.Insert(0, control);
                }
            }
        }
}

Hope this helps you!


Well, there are various ways you can accomplish a wizard, but the simplest would be to manage the UserControls from your main form. Just add an area to the main form that will be the parent of each user control and then add/remove a user control from the container when necessary.


The most elegant way to do this (I'd say the best) is using a Selector or a ListBox.

Your wizard will have several pages, each one exposes one or more informations, thus controls bound to some data. In other words, you should consider having a "model" containing the data, where the pages will bind to.

Now, consider having a distinct model for each page, and a list of these models feeding the ListBox. This ListBox should have defined its ItemTemplateSelector, that allows to choose a certain DataTemplate upon the item data (i.e. the model).

The hardest part of this technique is to create/define the Control template for the ListBox, that should be shaped for displaying only the selected item (SelectedItem). In such a way, you only have to change the current selection, and the wizard page will show automatically.

Although this technique appears an overkill, it is dramatically convenient respect to the "classic" approach. Your code is much more clean, easier to debug, reutilizable, and offers high separation between modules. All that will give much more reliability, and fast development.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜