Mohammed Abrar Ahmed
Mohammed Abrar Ahmed

Reputation: 2490

Display User Control(WPF) View page on click of a Button in WPF

There are many questions in this community for opening the window View on a click of a button just we need to create the instance of the view and use .Show and some question are based on using User Control in Window View.

I am following MVVM pattern to create a WPF application, in the Views I created a file called SalesView.xaml which is a User Control(WPF) view and by default I set the Dashboard.xaml from the App.xaml which is Window View and the project structure is some thing like this:

Project Structure

My requirement is that I have a button in Dashboard.xaml on click of this button I want to open a SalesView.xaml which is a User Control(WPF) view not a window View.

Upvotes: 2

Views: 2076

Answers (1)

VidasV
VidasV

Reputation: 4895

It seems like you need some short of shell for hosting your user controls. Simplest way is to put them on main window as content instead of a previous one. Or use some framework like Prism.

Normally how I would do it, I would create a class that is controller/view manager. And then pass in to it my view and vm, then the class would bind it and put it into the hosting window.

class ViewManager
{
   public void ShowView<T>(object viewModel) where T: UserControl, new()
   {
       var view = T();
       var window = new Window(); // feel free to prelace this simple approach with hosting shell
       view.DataContext = viewModel;
       window.Content = view;
       window.Show();
   }
}

Usage sample:

new ViewManager().ShowView<MyUserControl>(new MyViewModel());

Upvotes: 2

Related Questions