代码之家  ›  专栏  ›  技术社区  ›  4est

将数据从文本框分配到变量(c,wpf)

  •  0
  • 4est  · 技术社区  · 6 年前

    在XAML中,我有文本框:

    <TextBox Text="{Binding Path=LoginName}" Style="{StaticResource myTextBox}" />
    

    现在,我想将这个值赋给我的字符串变量(“userlogin”):

    private static string userLogin;
    public static void SetUser()
    {
            userLogin = LoginName.text; //ToString();
    }
    

    稍后进入其他方法,我将使用这个用户登录,如下所示:

    static async Task<string> SomeTest() {
    ...
      if (method == "authenticate")
          jsonString = "{.... + userLogin + ...}";
    ...
    }
    

    我做错什么了?应该怎么做?可能不需要setuser?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Julien Poulin    6 年前

    根据你的约束( Text="{Binding Path=LoginName}" )应该有一个公共财产 LoginName 类型的 string 在您的数据上下文中(在您的情况下,它似乎是视图本身):

    public string LoginName { get; set; }
    
    private static string userLogin;
    
    public static void SetUser()
    {
        // you can then use the property from here
        // (or remove `userLogin` altogether, as it does not add any value)
        // notice that we're not doing `.text` or anything; it's already a `string`
        userLogin = LoginName;
    }
    

    还有,莱昂尼德·马利舍夫 points out 如果你想要 登录名 要在每次按键时更新,需要在绑定中显式指定它,如下所示:

    <TextBox Text="{Binding Path=LoginName, UpdateSourceTrigger=PropertyChanged}" Style="{StaticResource myTextBox}" />
    

    否则,只有当 TextBox 失去焦点(默认行为)。


    解决此问题的另一种方法是移除绑定并引用 文本框 名字:

    <TextBox x:Name="LoginName" Style="{StaticResource myTextBox}" />
    

    然后您可以直接从代码访问它:

    private static string userLogin;
    
    public static void SetUser()
    {
        userLogin = LoginName.Text; // with an uppercase T!
    }