Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从LoginWindow到MainWindow获取字符串?_C#_.net_Wpf_Visual Studio - Fatal编程技术网

C# 从LoginWindow到MainWindow获取字符串?

C# 从LoginWindow到MainWindow获取字符串?,c#,.net,wpf,visual-studio,C#,.net,Wpf,Visual Studio,我有从应用程序启动时运行的LoginWindow.xaml。 我正在尝试将用户名字符串从登录窗口传递到主窗口 如果您正确登录,LoginWindow关闭,Main窗口打开,如何存储LoginWindow中的字符串 更新: 我正在尝试将我的用户名字符串存储在newTest.MyProperty中,但当它到达主窗口时为null 我遗漏了很多代码,因为很多代码都不相关。 代码示例: App.xaml LoginWindow.xaml.cs private void ButtonLogin_Click(

我有从应用程序启动时运行的LoginWindow.xaml。 我正在尝试将用户名字符串从登录窗口传递到主窗口

如果您正确登录,LoginWindow关闭,Main窗口打开,如何存储LoginWindow中的字符串

更新: 我正在尝试将我的用户名字符串存储在newTest.MyProperty中,但当它到达主窗口时为null

我遗漏了很多代码,因为很多代码都不相关。 代码示例: App.xaml

LoginWindow.xaml.cs

private void ButtonLogin_Click(object sender, RoutedEventArgs e)
    {
        StartUp();
        string userN = TextBoxUserName.Text;

        using (var db = dbFactory.Open())
        {
            db.CreateTableIfNotExists<User>();
            User newUser = db.Select<User>().Where(use => use.UserName.Equals(userN)).FirstOrDefault();
            if (true)
            {
                if (newEncrypt.GetMD5(TextBoxPassword.Text) == newUser.MasterPassword)
                {
                    Test newTest = new Test();
                    newTest.MyProperty = newUser.UserName;
                    this.Close();
                }

您正在为新的测试类实例设置此字段。您需要定义一个静态类。

到目前为止,您做得很好,但只有一件事

class Test
{
    public static string MyProperty { get; set; }
}
使用
static
string以
Test.MyProperty

为什么是静态的?因为where
static
变量在应用程序启动时创建,在应用程序关闭时删除,所以在关闭应用程序之前,您的数据仍将在那里,但如果您不使用
static
,则当您从当前类移动时,该值将被删除。

设置公共值
LoginWindow
类的
Username
属性:

public string Username { get; set; }
当用户登录时,设置它

然后,在执行
nLW.ShowDialog()
的代码之后,您可以获取
nLW.Username
属性,然后将其传递到
main窗口的
ctor
,该窗口将
字符串Username
作为参数:

nLW.ShowDialog(); // Your current code

var username = nLW.Username;
var mainWindow = new MainWindow(username);

mainWindow.Show();
编辑进一步提示:如果可能,请查看使用设计模式。它使您的代码更干净,模块化程度更高

与此相结合,研究如何使用
EventAggregator
在视图模型之间发送“消息”。我可以推荐,因为它可以很容易地完成所有这一切,并且非常容易设置


希望这有帮助!:)

在第一个关闭后运行的代码中,可能会打开第二个。您需要显示一些代码。我刚刚添加了一些代码。我添加了静态,现在我得到了一个错误“Member'Test.MyProperty'无法通过实例引用访问;请改为使用类型名对其进行限定”。这是因为您是通过实例访问的,在您的案例中直接与classname.propertyname一起使用
Test.MyProperty
表示不使用
Test Test=new Test()直接访问类即可
class Test
{
    public static string MyProperty { get; set; }
}
public string Username { get; set; }
nLW.ShowDialog(); // Your current code

var username = nLW.Username;
var mainWindow = new MainWindow(username);

mainWindow.Show();