Mit Jayani
Mit Jayani

Reputation: 13

how to change a user control form a button on anther user control in wpf?

I try to switch usercontrol using another usercontol button and the second usercontol is set on main window of wpf application,

for example

  1. main window of wpf application
  2. user_list usercontrol
  3. add_user usercontol

use user_list usercontrol button and switch add_user user control this usercontrol(add_user usercontrol) set on the main window

user_list.xamlenter image description here

  1. add_user.xaml

Upvotes: 0

Views: 776

Answers (1)

Corentin Pane
Corentin Pane

Reputation: 4933

You have a lot of ways to achieve this without using additional framework:

  • Have both user controls add_user and user_list in your MainWindow.xaml like this:
<Grid>
    <local:user_list x:Name="userList"></local:user_list>
    <local:add_user x:Name="addUser" Visibility="Hidden"></local:add_user>
</Grid>

And in your click event handler in your code-behind, switch the Visibility properties:

private void Button_Click(object sender, EventArgs e) {
    userList.Visibility = Visibility.Hidden;
    addUser.Visibility = Visibility.Visible;
    //Do other stuff like update data if needed
}
  • Only have the main UserControl user_list in your MainWindow like this:
<Grid>
    <local:user_list x:Name="userList"></local:user_list>
</Grid>

And create and display a new Window to display your add_user control in the code-behind:

private void Button_Click(object sender, EventArgs e) {
    var window = new Window();
    window.SizeToContent = SizeToContent.WidthAndHeight;
    window.Content = new add_user();
    window.ShowDialog() //blocking call
}
  • Instead of creating a new Window you could have your add_user control dynamically added to the visual tree of your existing MainWindow, like this:
<Grid>
    <local:user_list x:Name="userList"></local:user_list>
    <ContentControl x:Name="contentControl"></ContentControl>
</Grid>

And the code-behind:

private void Button_Click(object sender, EventArgs e) {
    contentControl.Content = new add_user();
}

Upvotes: 1

Related Questions