Question

I am new to MVVM. to learn I created a sample application to show a message in a text box while clicking on button. In my code the button command is working properly but the property is not binding to the Textbox. How to bind Property to Textbox using MVVM?

My code is similar like given 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));
        }
    }

}
Was it helpful?

Solution

  • in your model you have the textMessage as being an int rather than 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}"/>

OTHER TIPS

I don't understand your code but I guess you should fix your binding with this:

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

Where MyMessage should be a public property of MainViewModel

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top