How to sort/rearrange Views in StackPanel

Topics: Prism v4 - WPF 4
Sep 26, 2011 at 11:02 AM

Hi, I have a stack panel control which host as Region and many views will park inside, I have created a RegionAdapter for it and below is the sample code:

protected override void Adapt(IRegion region, StackPanel regionTarget)
        {
            if (region == null) return;

            region.Views.CollectionChanged += (sender, e) =>
            {
                switch (e.Action)
                {
                    case NotifyCollectionChangedAction.Add:
                        
                        // Add new view
                        foreach (UIElement element in e.NewItems)
                        {
                            regionTarget.Children.Add(element);
                        }
                        break;

                    case NotifyCollectionChangedAction.Remove:

                        foreach (UIElement elementLoopVariable in e.OldItems)
                        {
                            var element = elementLoopVariable;

                            if (regionTarget.Children.Contains(element))
                            {
                                regionTarget.Children.Remove(element);
                            }
                        }
                        break;
                }
            };
        }

I would like to re-arrange the view's position, for instance the topmost view may move to second position or bottom, or the view at middle move to top.


Is this possible in Prism 4?

Developer
Sep 26, 2011 at 8:29 PM

Hi,

Based on my understanding you could arrange your view's position using the ViewSortHint attribute. This attribute allows a view to declare a Hint property which defines how the view should be ordered in the region.

Note that by default when displaying views, the Region class uses a default view sorting routine that uses the hint to order the views.

You'll find more information regarding that in the Prism documentation, Chapter 7:

Also if you want to change how views are ordered the documentation explains that:

"...the Region class provides a SortComparison property that you can set with your own Comparison<object> delegate method. It is important to note that the ordering of the region's Views and ActiveViews properties are reflected in the UI because adapters such as the ItemsControlRegionAdapter bind directly to these properties. A custom region adapter could implement its own sorting and filter that will override how the region orders views."

I hope you find this useful.

Agustin Adami
http://blogs.southworks.net/aadami