Click the wpf button

I have a WPF application with 5 pages. In my main window, I have 5 buttons. What I would like to do is press button 1 to open page 1 in a frame in the main window. I do not want to use the navigation window. Should I use some kind of binding? I would like to use xmal, the smaller the code, the better. Thanks in advance for being at the training stages!

+4
source share
2 answers

You can set the Click buttons of event handlers to invoke Frame.Navigate (Uri) with its corresponding page.

In XAML:

<Frame Name="myFrame"/> <Button Name="buttonPage1" Click="OnClickPage1"> Page1 </Button> 

Then in the code behind:

 void OnClickPage1(object sender, RoutedEventArgs e) { myFrame.Navigate(new Uri("page1")); } 
+3
source

I assume that the logical continuation of your comments is that pressing button 2 will open page 2, etc.

My recommendation, and this applies to all WPF development, is to adopt MVVM. This will give you much greater flexibility and verifiability.

To implement your problem in MVVM:

Create ViewModels for each of your views and one for your main window

Each ViewModel becomes a DataContext for the corresponding view.

In MainWindowViewModel, implement 5 ICommand properties and assign the Command property on the button to each corresponding ICommand property in MainWindowViewModel.

In the main window, I'm not sure if you are using a Frame control, but I would suggest using the ContentControl to bind the Content property to the control to some property of type Object in MainWindowViewModel.

When executing each of the ICommand objects, you must set the MainWindowViewModel content property to the appropriate ViewModel for this button.

In MainWindowView.xaml, you will need to implement a series of DataTemplates that display the ViewModel in the View:

 <DataTemplate DataType="{x:Type Page1ViewModel}"> <AdornerDecorator> <views:Page1View DataContext="{Binding}"/> </AdornerDecorator> </DataTemplate> 

I would advise you to take a look at using one of the many available MVVM frameworks.

MVVMFoundation - light weight, minimal implementation

MVVMLight - heavier structure

Caliburn - There seems to be a lot of extra features

The implementation of the full structure may seem like a lot of additional work, but it will cost in the end, more subject to verification, more convenient to maintain.

+1
source

Source: https://habr.com/ru/post/1342201/


All Articles