简体   繁体   中英

How Can I Pass var between pages in C# WPF

How can I pass var between pages in C# WPF. For example I have my int in Page1.xaml.cs and how can I pass this var to Page1.xaml.cs

Page1.xaml.cs

int var = 1;
private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            How can I after press button send var to page2
        }
int var = 1;
private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        Page2(var);
    }

In page 2 you will need something to pass in var

public Page2(int var)
{

}

It depends on how the Pages are related. For example

When Page1 creates Page2 , I would pass the var variable via the constructor of Page2 . If you need to call some methods, you can't add it there.

If Page1 and Page2 don't share any relation, the most easiest is a singleton (static) instance, which could be accessed by both, but it would be hard to make tests for. There are some better implementations like Dependency Injection which is more testfriendly. Start at the beginning.

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