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

2

10

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

}
Frenzied answered 8/2, 2012 at 12:22 Comment(2)
Please post some more code as the one you posted can be incorrectly interpreted. Do you have a separate TestMessage property in your VM which exposes the model's TestMessage?Bartonbartosch
No Don't Have. That was the mistake. from the Answers Posted here I understood how to do this. Thank You.Frenzied
M
15
  • 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}"/>
Morganmorgana answered 8/2, 2012 at 12:41 Comment(0)
E
5

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

Enabling answered 8/2, 2012 at 12:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.