假设我们有一个模型(类别Model
)具有以下属性。如何在ViewModel更改后正确更新模型?
public string InputFileName
{
get { return m_InputFileName; }
set
{
m_InputFileName = value;
RaiseNotifyPropertyChanged("InputFileName");
}
}
上述模型实现INotifyPropertyChanged
接口,所以我们也有以下方法和以下的事件。下面的RaiseNotifyPropertyChanged
方法用于更新ViewModel。
#region INotifyPropertyChanged Implementation
private void RaiseNotifyPropertyChanged(string property)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(property));
}
}
public event PropertyChangedEventHandler PropertyChanged;
#endregion
以下是实现视图模型类的主要部分。
public class ViewModel : INotifyPropertyChanged
{
#region Members
private Model m_Model;
private string m_InputFileStr;
private readonly ICommand m_SubmitCommand;
#endregion
#region Constructors
public ViewModel()
{
m_Model = new Model();
m_Model.PropertyChanged += new PropertyChangedEventHandler(this.Model_PropertyChanged);
m_InputFileStr = string.Empty;
// ...
// initialize m_SubmitCommand
}
#endregion
// ...
#region Properties
public string InputFileStr
{
get { return m_InputFileStr; }
set
{
if (value == m_InputFileStr) return;
m_InputFileStr = value;
OnPropertyChanged("InputFileStr");
m_SubmitCommand.RaiseCanExecuteChanged();
}
}
#endregion
#region INotifyPropertyChanged Implementation
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
// This method is called when the model changes, so the Model notified the ViewModel.
private void Model_PropertyChanged(object sender, PropertyChangedEventArgs args)
{
if (args.PropertyName == "InputFileName")
{
InputFileStr = m_Model.InputFileName;
}
else if (args.PropertyName == "OutputFileName")
{
OutputFileStr = m_Model.OutputFileName;
}
else if (args.PropertyName == "ReportText")
{
ReportTextStr = m_Model.ReportText;
}
}
}
以下是实现查看类的主要部分:
MainWindow.xaml
<TextBox Name="inputfileTextBox"
Text="{Binding Path=InputFileStr, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>
<Button Name="submitButton"
Content="Submit"
Command="{Binding SubmitCommand}"/>
MainWindow.xaml.cs
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new ViewModel();
}
}
的以上实现工作正常:
- View和ViewModel正确更新对方;
- 模型正确更新ViewModel。
带启用视图模型更新模型的目的,我想我会添加以下调用集合属性视图模型的InputFileStr
内:
m_Model.InputFileName = value;
然而,更新模型原因的这一解决方案一个明显的意想不到的影响:
- 用户修改视图。
- ViewModel自动修改。
- ViewModel更新模型(
m_Model.InputFileName = value;
)。 - 模型更新...
- ...所以它会通知视图模型有关的变化
是上述行为正确的行为?我期望如果ViewModel更新模型,那么模型不必重新通知ViewModel有关相同的更改......作为替代解决方案,我认为我会为模型添加一个Update
方法:此方法应该更新该模型不使用模型属性。
public void Update(string inputFileName) // this method does not notifies the ViewModel
{
m_InputFileName = inputFileName;
}
此替代解决方案是正确的解决方案还是有更好的解决方案?