简体   繁体   中英

WPF How do I return value to the main program from Button Click

I am new to WPF and C# and cannot understand how to return a value from inside a Button_Click .

I am trying to get the user to select a file location then pass that location to the main program. Here is my code so far which works but I cannot pass the string back.

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }   

    public static string Button_Click(object sender, RoutedEventArgs e)
    {
        var dialog = new System.Windows.Forms.FolderBrowserDialog();
        System.Windows.Forms.DialogResult result = dialog.ShowDialog();
        string FolderLocation  = dialog.SelectedPath; //this is c:/folder

        return FolderLocation;
    }

    // need to use FolderLocation here to do some stuff.
}

So as I read you are new at C# so you need to read about global variables. For now I will help you with this simple sample:

    public MainWindow()
    {
        InitializeComponent();
    }

    public string globalVariable; //this is global variable (easiest one)

    public static string Button_Click(object sender, RoutedEventArgs e)
    {


        var dialog = new System.Windows.Forms.FolderBrowserDialog();
        System.Windows.Forms.DialogResult result = dialog.ShowDialog();
        string FolderLocation  = dialog.SelectedPath; //this is c:/folder


        globalVariable=FolderLocation;

    }
    public void MethodX()
    {
     string variableWithValueFromButtonClick=globalVariable;
    //U can use your globalVariable here or wherever u want inside class MainWindow

    }

And here you have some tutorial

The code in your question shouldn't even compile. The signature of the Button_Click event cannot have a return value.

While it's also an option to store this selection in a "global" variable, this doesn't solve the dilemma of what to do with the selection once it's stored there. Unless the state of the selection needs to be maintained, the better solution is to immediately pass it to a method that will consume the information.

public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var dialog = new System.Windows.Forms.FolderBrowserDialog();
            System.Windows.Forms.DialogResult result = dialog.ShowDialog();
            ProcessFolderLocation(dialog.SelectedPath);
        }

        private void ProcessFolderLocation(string location)
        {
            // ... Do something with your selected folder location
        }
    }

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