如何使用 MVVM 和 MVVM 工具包将属性绑定到文本框? [英] How To Bind a Property to Textbox using MVVM and MVVM toolkit?

查看:77
本文介绍了如何使用 MVVM 和 MVVM 工具包将属性绑定到文本框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 MVVM 的新手.为了学习,我创建了一个示例应用程序,用于在单击按钮时在文本框中显示一条消息.在我的代码中,按钮命令工作正常,但该属性未绑定到文本框.如何使用 MVVM 将属性绑定到文本框?

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.

查看

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

查看模型

MyMessage myMessage; 
public MainViewModel()
{
myMessage=new MyMessage();
}

//inside the ShowCommand Handler

TestMessage="Hello World";

// A Property to set TextBox Value. 

型号

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

}

推荐答案

  • 在您的模型中,您的 textMessage 是 int 而不是字符串?
  • 尝试这样的事情:

    视图模型

     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!";
    

    模型

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

    这篇关于如何使用 MVVM 和 MVVM 工具包将属性绑定到文本框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆