XAML data binding to a global variable?
如何在XAML中将TextBoxes文本绑定到类中的全局变量?
顺便说一句,这是针对Windows Phone的。
这是代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | namespace Class { public partial class Login : PhoneApplicationPage { public static bool is_verifying = false; public Login() { InitializeComponent(); } private void login_button_Click(object sender, RoutedEventArgs e) { //navigate to main page NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.RelativeOrAbsolute)); } private void show_help(object sender, EventArgs e) { is_verifying = true; } } } |
我想将文本框文本绑定到" is_verifying"。
谢谢。
首先,您只能绑定到属性,因此需要添加一个getter和setter。
1 | public static bool is_verifying { get; set; } |
接下来,您可以在此处将表单的
1 | "{Binding is_verifying}" |
或者在表单的资源中创建对您的类的引用,然后像这样引用它:
1 2 3 4 5 6 | <Window.Resources> <local:Login x:Key="LoginForm"/> </Window.Resources> ... <TextBox Text="{Binding Source={StaticResource LoginForm}, Path=is_verifying}"/> |
您无法绑定到字段,需要将其设置为属性,而且,除非您实现某种通知机制(例如可以实现),否则不会通知您更改。通过实现
拥有属性后,通常可以使用
但是绑定到静态属性需要一些技巧,在您的情况下可能不起作用,因为它们需要创建类的虚拟实例或使其成为单例。我也认为至少在Windows Phone 7