将变量从窗口传递到页面

我想将我插入Window的文本框中的变量传递给WPF应用程序中的Page,我才发现我该怎么做。

基本上我需要应用提示输入密码,该密码需要在其他页面中使用。

我从这样的页面调用窗口:

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

这只是一个带有文本框和按钮的窗口,输入密码并单击“确定”后,我想将密码从称为窗口的页面发送到页面上的变量中。

wuxiuhao 回答:将变量从窗口传递到页面

最有效的方法是单击窗口上的按钮并从页面预订该事件,从而引发一个事件。

窗口

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添加一个属性,该属性返回TextTextBox的{​​{1}}属性的值:

PasswordBox

XAML:

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

然后您可以使用此属性检索密码。您可能还希望阻塞调用线程,直到关闭窗口为止。然后,您应该呼叫<PasswordBox x:Name="_passwordBox" /> 而不是ShowDialog()

Dialog()

另一种选择是处理Password_Prompt PassWindow = new Password_Prompt(); PassWindow.ShowDialog(); string password = PassWindow.Password; 事件:

Closed
本文链接:https://www.f2er.com/3050019.html

大家都在问