无法使用 MVVM 体系结构将数据绑定到文本框
本文关键字:数据绑定 文本 体系结构 MVVM | 更新日期: 2023-09-27 18:37:08
我是MVVM和WPF的新手。我尝试使用DataContext将数据绑定到文本框。
型号: 我的留言.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));
}
}
视图模型:主视图模型.cs
class MainViewModel
{
MyMessage myMessage;
public MainViewModel()
{
myMessage = new MyMessage();
myMessage.TestMessage="Hai";
}
查看 : 主窗口.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"转换为属性,并在TextBox
中将其MyMessage.TestMessage
绑定,假设您将MainViewModel
绑定为Window
中的DataContext
。
试试这个:
class MainViewModel
{
private MyMessage _messageProperty;
public MyMessage MessageProperty
{
get { return _messageProperty; }
set { _messageProperty = value; }
}
public MainViewModel()
{
_messageProperty = new MyMessage();
_messageProperty.TestMessage="Hai";
}
此外,OnPropertyChanged 事件中的字符串必须与属性同名,如下所示:
public string TestMessage
{
get { return testMessage; }
set
{
testMessage = value;
OnPropertyChanged("TestMessage");
}
}
在 MainWindow.xaml.cs 的代码隐藏文件中,将数据上下文设置为 ViewModel:
class MainWindow
{
public MainWindow()
{
this.DataContext = new MainViewModel();
}
在 MainWindow.xaml 文件中,您必须引用 MessageProperty 的嵌套属性
<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 MessageProperty.TestMessage}" VerticalAlignment="Top" Width="120"/>
</Grid>
让我知道它是否有效,如果您需要更多信息;-)此外,我建议您制作一个快速入门教程,了解 MVVM 的工作原理及其实现方式,例如 http://www.codeproject.com/Articles/165368/WPF-MVVM-Quick-Start-Tutorial