将变量从 window 传递到页面

Pass variable from window to page

我想将我插入 Window 中的文本框的变量传递给 WPF 应用程序中的页面,我只发现我怎么能用其他方式做到这一点。

基本上我需要应用程序来提示我需要在不同页面中使用的密码。

我从这样的页面调用 window:

Password_Prompt PassWindow = new Password_Prompt();
PassWindow.Show();

只是 window 带有一个文本框和一个按钮,在我输入密码并单击确定后,我想将密码发送到我调用 window 的页面上的变量中。

实现此目的的最有效方法是在您单击 window 上的按钮并从页面订阅它时引发事件。

Window

public event EventHandler<string> PasswordInput;

// the function you are going to call when you want to raise the event
private void NotifyPasswordInput(string password)
{
    PasswordInput?.Invoke(this, password);
}

// button click event handler
private void OnButtonClick(object sender, RoutedEventArgs e)
{
    // get the password from the TextBox
    string password = myTextBox.Text;

    // raise the event
    NotifyPasswordInput(password);
}

页数

...
Password_Prompt PassWindow = new Password_Prompt();

// add this part to subscribe to the event
PassWindow.PasswordInput += OnPasswordInput;

PassWindow.Show();
...

// and the method to handle the event
private void OnPasswordInput(object sender, string password)
{
    // use the password from here
}

您可以添加一个 属性 到 PassWindow.xaml.cs 即 returns Text 的值 属性 或 TextBoxPasswordBox:

public string Password
{
    get { return _passwordBox.Password; }
    set { _passwordBox.Password = value; }
}

XAML:

<PasswordBox x:Name="_passwordBox" />

然后您可以使用此 属性 检索密码。您可能还想阻塞调用线程,直到 window 关闭。那么你应该调用 ShowDialog() 而不是 Dialog():

Password_Prompt PassWindow = new Password_Prompt();
PassWindow.ShowDialog();
string password = PassWindow.Password;

另一种选择是处理 Closed 事件:

Password_Prompt PassWindow = new Password_Prompt();

EventHandler handler = null;
handler =  (s, e) => 
{
    string password = PassWindow.Password;
    PassWindow.Closed -= handler;
};
PassWindow.Closed += handler;

PassWindow.Show();