我是MVVM的新手。为了学习,我创建了一个示例应用程序,在单击按钮时在文本框中显示消息。在我的代码中,button命令工作正常,但属性没有绑定到Textbox。如何使用MVVM将属性绑定到文本框?
我的代码如下所示。
查看
<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而不是字符串
试试这样的东西:
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!";
型号
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}"/>
我不理解您的代码,但我想您应该用以下代码修复绑定:
<TextBox Name="MessageTextBox" Text="{Binding MyMessage.TestMessage}"/>
其中MyMessage
应该是MainViewModel
的公共属性