我是MVVM和WPF的新手。我试图使用DataContext将数据绑定(bind)到文本框。
模型:MyMessage.cs
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));
}
}
ViewModel:MainViewModel.cs
class MainViewModel
{
MyMessage myMessage;
public MainViewModel()
{
myMessage = new MyMessage();
myMessage.TestMessage="Hai";
}
View :MainWindow.xaml
<Window x:Class="DemoApp2.Views.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBox HorizontalAlignment="Left" Height="23" Margin="10,10,0,0" TextWrapping="Wrap" Text="{Binding TestMessage}" VerticalAlignment="Top" Width="120"/>
</Grid>
最佳答案
您需要将“myMessage”转换为属性,并在MyMessage.TestMessage
中将其绑定(bind)为TextBox
,前提是您在MainViewModel
中将DataContext
绑定(bind)为Window
。
关于c# - 无法使用MVVM架构将数据绑定(bind)到文本框?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27899669/