How to associate a property with a text field using the MVVM and MVVM toolkit?

I am new to MVVM. to find out, I created a sample application to show a message in a text box when a button is clicked. In my code, the button command works correctly, but the property is not bound to a text field. How to bind a property to a text field using MVVM?

My code is similar to below.

View

<TextBox Name="MessageTextBox" Text="{Binding TestMessage}"/> <Button Content="Show" Name="button1" Command="{Binding ShowCommand}"> <!-- Command Handler --> </Button> 

View Model

 MyMessage myMessage; public MainViewModel() { myMessage=new MyMessage(); } //inside the ShowCommand Handler TestMessage="Hello World"; // A Property to set TextBox Value. 

Model

 public class MyMessage: INotifyPropertyChanged { private string testMessage; public string TestMessage { get { return testMessage; } set { testMessage= value; OnPropertyChanged("TestName"); } } public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged(string propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } 
+7
source share
2 answers
  • In your model, do you have textMessage as an int, not a string?

try something like this:

ViewModel

  private MyMessage message; public MainViewModel() { message = new MyMessage(); } public MyMessage Message { get { return message;} set { message = value;} } //in your command: this.Message.TestMessage = "Hello World!"; 

MODEL

 public class MyMessage: INotifyPropertyChanged { private string testMessage public string TestMessage; { get{ return testMessage; } set { testMessage = value; this.OnPropertyChanged("TestMessage"); } } //INotifyChanged Events } 

Xaml

 <TextBox Text="{Binding Message.TestMessage, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/> 
+12
source

I do not understand your code, but I think you should fix your binding with this:

 <TextBox Name="MessageTextBox" Text="{Binding MyMessage.TestMessage}"/> 

Where MyMessage should be a public property of MainViewModel

+5
source

All Articles