在其他页面上显示用户名?代码错误

时间:2019-02-21 18:55:46

标签: c# azure uwp

代码已经创建,但是给了我一个小错误。这是用于在第一个登录页面中保存用户名的代码。

public void SaveSetting(string userLabel, string userNamelabel)
    {
        ApplicationDataContainer localSettings =
        ApplicationData.Current.LocalSettings;
        //Saving your setting  
        localSettings.Values[userLabel] = textBoxUsername.Text;
    }

我的主页上

public home()
    {
        this.InitializeComponent();
        UserNameLabelBox.Text = ReadSetting(userLabel);
    }



private string ReadSetting(string userLabel)
    {
        Windows.Storage.ApplicationDataContainer localSettings =
        Windows.Storage.ApplicationData.Current.LocalSettings;
        //Reading and returning your setting value
        var value = localSettings.Values[userLabel];
        if (value != null)
            return value.ToString();
        else
            return userLabel;

初始化组件下面的行以红色突出显示,并表示“ userLabel在当前上下文中不存在”。

1 个答案:

答案 0 :(得分:0)

似乎您从未将主页上变量userLabel的值设置为可以从另一页看到的变量。

我将向您的登录页面添加一个名为public string globalUserLabel ;的公共全局变量,然后在您的主页home方法中调用它。

喜欢:

public string globalUserLabel;

public void SaveSetting(string userLabel, string userNamelabel)
    {
        globalUserLabel = userLabel;
        ApplicationDataContainer localSettings =
        ApplicationData.Current.LocalSettings;
        //Saving your setting  
        localSettings.Values[userLabel] = textBoxUsername.Text;
    }


public home()
    {
        this.InitializeComponent();
        UserNameLabelBox.Text = ReadSetting(LoginPage.globalUserLabel );
    }

OR

您可以创建一个globalVariable类,并将用户信息存储在该类中,并在必要时调用此特定类。

看起来像

public class globalVariable {

public string userlabel {get; set;};

}

然后

public void SaveSetting(string userLabel, string userNamelabel)
    {
        globalVariable.userlabel = userLabel;
        ApplicationDataContainer localSettings =
        ApplicationData.Current.LocalSettings;
        //Saving your setting  
        localSettings.Values[userLabel] = textBoxUsername.Text;
    }

最后

public home()
    {
        this.InitializeComponent();
        UserNameLabelBox.Text = ReadSetting(globalVariable.userlabel);
    }