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

牧云@^-^@ 提交于 2019-12-07 01:31:05

问题


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

}

回答1:


  • 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}"/>



回答2:


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



来源:https://stackoverflow.com/questions/9193221/how-to-bind-a-property-to-textbox-using-mvvm-and-mvvm-toolkit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!