簡體   English   中英

WPF如何從Button單擊返回值到主程序

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

我是WPF和C#的新手,無法理解如何從Button_Click內部返回值。

我試圖讓用戶選擇一個文件位置,然后將該位置傳遞給主程序。 到目前為止,這是我的代碼,可以正常工作,但是我無法將字符串傳遞回來。

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.
}

因此,如我所讀,您是C#的新手,因此您需要閱讀有關全局變量的信息。 現在,我將通過以下簡單示例幫助您:

    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

    }

這里有一些教程

您問題中的代碼甚至不應編譯。 Button_Click事件的簽名不能有返回值。

雖然也可以將此選擇存儲在“全局”變量中,但是這並不能解決將選擇存儲到那里后如何處理的難題。 除非需要保持選擇狀態,否則更好的解決方案是立即將其傳遞給使用該信息的方法。

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
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM