简体   繁体   English

TextBox控件未更新.Text属性

[英]TextBox Control Not Updating .Text property

Can anyone shed light on this issue? 谁能阐明这个问题?

I have a bunch of controls creating in a class 我在课堂上创建了一堆控件

public static TextBox uname = new TextBox { PlaceholderText = "Username", Margin = new Thickness(0, 5, 0, 0), Text = MainPage.UNAME };

When I call the database to update the UNAME field on the mainpage, it does and I can print the new value. 当我调用数据库更新主页上的UNAME字段时,它确实可以打印新值。 However, The textBox that is shown above which resides in a different class does not update to the new value. 但是,上面显示的位于不同类中的textBox不会更新为新值。

I've tried initializing this textbox after the database gets the values but no luck. 我尝试在数据库获取值但没有运气之后初始化此文本框。

Any help is appreciated. 任何帮助表示赞赏。

The uname TextBox is instantiated and assigned when your Page is created. 创建页面时,将实例化并分配uname的TextBox。 Although you call the database to update the MainPage.UNAME but you have not changed the pointer content of uname.Text . 尽管您调用数据库来更新MainPage.UNAME但是您尚未更改uname.Text的指针内容。 The easy way you can set uname.Text directly like uname.Text = MainPage.UNAME . 您可以像uname.Text = MainPage.UNAME一样直接设置uname.Text的简单方法。

You can also use xaml data Binding like code behind. 您还可以在后面使用xaml数据绑定之类的代码。

MainPage.xaml.cs MainPage.xaml.cs

 public ViewModel viewModel { get; set; }      
 public MainPage()
 {          
     this.InitializeComponent();
     this.viewModel = this.DataContext as ViewModel;

 }

 private void MyButton_Click(object sender, RoutedEventArgs e)
 {   
     viewModel.Uname = MainPage.UNAME;
 }

MainPage.xaml MainPage.xaml

<TextBox
    Margin="0,0,5,0"
    PlaceholderText="User Name"
    Text="{Binding Path=Uname}" />

ViewModel.cs ViewModel.cs

public event PropertyChangedEventHandler PropertyChanged;
private string uname;
public string Uname
{
    get
    {
        return uname;
    }

    set
    {
        uname = value;
        OnPropertyChanged();
    }
}

public void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
    PropertyChangedEventHandler eventHandler = this.PropertyChanged;
    if (eventHandler != null)
    {
        eventHandler(this, new PropertyChangedEventArgs(propertyName));
    }
}

I figured out a way around it. 我想出了办法。

I changed this line: 我更改了这一行:

public static TextBox uname = new TextBox { PlaceholderText = "Username", Margin = new Thickness(0, 5, 0, 0), Text = MainPage.UNAME };

To this: 对此:

public static TextBox uname = new TextBox { PlaceholderText = "Username", Margin = new Thickness(0, 5, 0, 0) };

Then put all my Text assignments in the initialization method. 然后将我所有的Text分配都放在初始化方法中。

ex. 例如 , uname.Text = MainPage.UNAME ,uname.Text = MainPage.UNAME

Then.. I called the init after the DB call and poof it worked! 然后..我在数据库调用之后调用了init并对其进行了调试!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM