我已经按照一些教程创建了一个非常简单的MVVM" test"了解它是如何工作的。根据我的理解:
据我了解,这些不应该互相交谈。 View不应该每次绑定到Model数据,View Model都不应该与数据库通信。
然而,当我开始做一些例子时,我发现并没有这样做。我基于此创建了我的示例:
https://rachel53461.wordpress.com/2011/05/08/simplemvvmexample/
而且这个:
http://www.codeproject.com/Articles/126249/MVVM-Pattern-in-WPF-A-Simple-Tutorial-for-Absolute
它是一个简单的组件,用于保存和加载来自"数据库的文本。 (它不存在):
模型
class TestModel : ObservableObject
{
#region Fields
private String _text;
#endregion
#region Public Properties & Commands
public String Text
{
get { return _text; }
set
{
if (value != _text)
{
_text = value;
OnPropertyChanged("Text");
}
}
}
#endregion
}
查看模型
class TestViewModel : ObservableObject
{
#region Fields
private TestModel _currentTestModel;
private ICommand _saveTextCommand;
private ICommand _loadTextCommand;
#endregion
#region Public Properties & Commands
public TestModel CurrentModel
{
get
{
return _currentTestModel;
}
set
{
if (value != _currentTestModel)
{
_currentTestModel = value;
OnPropertyChanged("CurrentModel");
}
}
}
public ICommand SaveTextCommand
{
get
{
if (_saveTextCommand == null)
{
_saveTextCommand = new RelayCommand(param => SaveModel(), param => true);
}
return _saveTextCommand;
}
}
public ICommand LoadTextCommand
{
get
{
if (_loadTextCommand == null)
{
_loadTextCommand = new RelayCommand(param => LoadModel(), param => true);
}
return _loadTextCommand;
}
}
#endregion
#region Methods
public void LoadModel()
{
//gets from "database" (currently created)
TestModel TestModel = new TestModel();
TestModel.Text = "Initial Text From View Model";
CurrentModel = TestModel;
}
public void SaveModel()
{
//saves to "database" (currently just console output)
Console.WriteLine("Saving: " + CurrentModel.Text);
}
#endregion
}
查看
<UserControl x:Class="MVVM_Test.TestView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:MVVM_Test"
mc:Ignorable="d">
<UserControl.DataContext>
<local:TestViewModel/>
</UserControl.DataContext>
<StackPanel Width="215">
<TextBox Text="{Binding Path=CurrentModel.Text}"/>
<Button Command="{Binding Path=LoadTextCommand}" Content="load"/>
<Button Command="{Binding Path=SaveTextCommand}" Content="save"/>
</StackPanel>
具体问题:
_saveTextCommand = new RelayCommand(param => CurrentModel.SaveModel(), param => true);