WPF如何从Button Click返回主程序的值

时间:2015-11-15 23:12:18

标签: c# wpf events

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

2 个答案:

答案 0 :(得分:0)

因此,当我读到你是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

    }

here你有一些教程

答案 1 :(得分:0)

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