Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Bind a Property to Textbox using MVVM and MVVM toolkit?

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));
        }
    }

}
like image 410
niknowj Avatar asked Feb 08 '12 12:02

niknowj


1 Answers

  • 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}"/>
like image 84
emybob Avatar answered Oct 06 '22 22:10

emybob