Betsy
Betsy

Reputation: 51

wpf button click

I Have a WPF app with 5 pages. On my main window I have 5 buttons. What I would like to do is click button 1 to open page 1 in a frame on the main window. I dont want to use a navagation window. Should I use some kind of binding? I would like to use xmal, the less code the better. Thanks in advance I'm in the learning stages!

Upvotes: 4

Views: 9159

Answers (2)

benPearce
benPearce

Reputation: 38373

I assume that the logical follow-on from your comments is that pressing button 2 will open page 2 etc.

My recommendation, and this goes for all WPF development, is to adopt MVVM. It will give you a lot more flexibility and testability.

To implement your problem in MVVM:

Create ViewModels for each of your views, and one for your Main window

Each ViewModel becomes the DataContext for its respective View.

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

On the main window, I am not sure if you are implementing a Frame control, but I would suggest using a ContentControl, bind the Content property on the control to some property of type Object on the MainWindowViewModel.

In the execution of each of the ICommand objects, you would set the content property on the MainWindowViewModel to the matching ViewModel for that button.

In the MainWindowView.xaml you would need to implement a series of DataTemplates which map the ViewModel to a View:

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

I would suggest that you look at using one of the many MVVM frameworks available.

MVVMFoundation - light weight, bare minimum implementation

MVVMLight - heavier framework

Caliburn - seems to have a lot of additional functionality

Implementing a full framework might seem like a lot of extra work but it will be worth it in the long run, more testable, more maintainable.

Upvotes: 1

tugudum
tugudum

Reputation: 397

You could set your buttons' Click event handlers to call Frame.Navigate(Uri) with their respective 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"));
}

Upvotes: 3

Related Questions