Click here to Skip to main content
15,886,110 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi everyone, I'm trying to bind a string to textblock and textbox in UWP. What I am trying to achieve is simply updating the textblock and textbox when a button is pressed. So far, the initial binding works perfectly, the ICommand execution is also okay, the string got changed when the button is pressed. However, the updated string is not updated on the textblock and textbox. code is as follows:

MainPage.xaml
XML
<StackPanel>
   <TextBlock text="{x:bind vm.TestString, Mode=OneWay}"/>
   <TextBox text="{Binding TestString, Mode=TwoWay, UpdateSourceTrigger=OnPropertyChanged}" />
   <Button Content="Press Me" ICommand="{Binding Cmd}"/>
</StackPanel>


MainPage.xaml.cs
C#
ViewModel vm = new ViewModel();

public MainPage()
{
   this.DataContext = vm;
   this.InitializeComponent();
}


RelayCommand.cs
C#
public event EventHandler CanExecuteChanged;

private readonly Action execute;
private readonly Predicate<object> canExecute;

public bool CanExecute(object parameter)
{
  return canExecute == null ? true : canExecute(parameter);
}

public void Execute(object parameter)
{
  this.execute();
}

public RelayCommand(Action exec, Predicate<object> canExec)
{
  execute = exec;
  canExecute = canExec;
}


The viewmodel.cs inherits from INotifyPropertyChanged
C#
public event PropertyChangedEventHandler PropertyChanged;

protected void OnPropertyChanged(string PropertyName)
{
   PropetyChangedEventHandler hndl = this.PropertyChanged;

   if (hndl == null)
   {
      var e = new PropertyChangedEventArgs(PropertyName);
      hndl(this,e);
   }
}

private string testString;

public string TestString
{
   get {return testString;}
   set 
   {
      testString= value;
      OnPropertyChanged("TestString");
   }
}

public ViewModel()
{
   testString = "This is the original text";
}

public ICommand Cmd
{
   get { return new RelayCommand(() => this.ChangeString(), param => true);} 
}

private void ChangeString()
{
   testString = "String is Changed";
}


What I have tried:

I read that unlike in WPF, textblock in UWP are one time binding by default. I tried changing it to one way and also two way but the textblock and textbox still wouldn't update. I also tried to set the update source trigger to on property changed, still no go
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900