Sandeep Bansal
Sandeep Bansal

Reputation: 6394

Dynamic views in WPF

I'm trying to dynamically change UserControl views that are defined in an ObservableCollection.

public class MItem : INotifyPropertyChanged
    {
        private UserControl _mView;
        public UserControl MView
        {
            get { return _mView; }
            set
            {
                if (_mView != value)
                {
                    _mView = value;
                    OnPropertyChanged("MView");
                }
            }
        }

...
        }

In a separate view I have:

ObservableCollection<MItem> _items = new ObservableCollection<MItem>;

_items.Add(new MItem{MView = MyView});

Obviously when it comes to create a new object of that view and then assigning it to a child on a Grid comes to be a problem - It'll give me a type error.

I've tried something like:

_items[0].MView = new UserControl(); // I know this wouldn't work

My main question is, has anyone tried implementing something like this and how did you get around it?

Thanks

Upvotes: 0

Views: 5648

Answers (1)

Brian S
Brian S

Reputation: 5785

As @HighCore indicates, WPF allows for a much better way of dynamically determining what view to display, while maintaining a separation of concerns so you're not mixing view logic with business logic. And MVVM is the tried and true method of accomplishing this.

Essentially, what you want to do is create a ViewModel for each "thing" you want to display. Then, you create a DataTemplate for each ViewModel which is the View. The DataTemplate could be self contained, or it could just point to a UserControl. Then, you use a ContentPresenter which is DataBound to a CurrentItem property, or something, and when you set the CurrentItem to a specific ViewModel, WPF will locate the appropriate DataTemplate (View) for you and display it accordingly.

There are several walkthroughs on the web that demonstrate this, and there are also several examples of this pattern on StackOverflow as well. One example that seems to match very closely what you're asking for is here: Switching between Views/UserControls using MVVM.

Upvotes: 9

Related Questions