【发布时间】:2012-02-29 21:10:35
【问题描述】:
我是 MVVM 的新手。为了了解我创建了一个示例应用程序,以便在单击按钮时在文本框中显示一条消息。在我的代码中,按钮命令正常工作,但该属性未绑定到文本框。如何使用 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));
}
}
}
【问题讨论】:
-
请发布更多代码,因为您发布的代码可能会被错误解释。您的 VM 中是否有单独的 TestMessage 属性来公开模型的 TestMessage?
-
不,没有。那是错误。从此处发布的答案中,我了解了如何执行此操作。谢谢。
标签: wpf mvvm mvvm-toolkit