WPF我如何从按钮点击返回值到主程序



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

问题中的代码甚至不应该编译。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
        }
    }

所以,正如我所读到的,你是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
    }

这里有一些教程

最新更新