简体   繁体   中英

Change content of WPF Window

When I click on a Button on my navigation bar, a new Window opens. For example:

    private void btFinanzen_Click(object sender, RoutedEventArgs e)
    {
        Finanz mw = new Finanz(login);
        mw.Show();

    }

Now, I don´t want to show it in a new window. Instead of that, I want it to be shown at the same window. I tried with the following:

    private void btFinanzen_Click(object sender, RoutedEventArgs e)
    {
        Finanz mw = new Finanz(login);
        //mw.Show();
        this.Content = Finanz f;

    }

but it failed. What I should say is, that I´ve many of different windows now and want them all to be shown at one window - each by clicking a different button. How can I manage this?

What you have to do is to use a UserControl rather than a Window for your replaceable content. Add a new UserControl for each possible content you want to show in this.Content to your project. Add the content you had previously in the second window to the appropriate UserControl. After that you can simply instantiate the new control in your code and assign it to your content area of your main Window.

For example you create a UserControl ctlFinanz with the content of your previous Finanz window. Now you simply write:

this.Content = new ctlFinanz(login);

That's all :-)

我遇到了同样的问题,并决定为每个窗口创建一个单独的用户控件,将它们放在我的 wpf 中,并将除活动窗口之外的所有窗口的可见性设置为折叠。

Create a main content with a UserControl that I set into the window constructor. And then I change the content with other UserControl depending on your needs.

MainWindow constructor:

this.Content = new UserControlMainContent();

From UserControlMainContent , when I click on a button by example:

Window window = Window.GetWindow(this); // Get the main window
window.Content = new OtherUserControlContent();

To me, this sounds like place to use a frame with pages. Instead of making lots of windows, make one window with a frame, then put the content into pages. Then all you have to do is change the frame's .Content to a different page each time you press a navigation button.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM