根据你的约束(
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!
}