创建一个新类 ApplicationModel 来保存所有用户数据。您的“主”视图模型应该创建它,然后将它保存在一个属性中。您的视图需要绑定到模型中数据的完整路径:
<DataGrid ItemsSource="{Binding Path=Model.ListOfThingsToDo, Mode=OneWay}" ... />
在新 ViewModel 的构造函数中,您将该模型作为参数提供。这样,您的所有 ViewModel 将共享相同的模型,并且新的 ViewModel 可以修改/查看与您的“主” ViewModel 相同的数据。
/// <summary>
/// ViewModel for the Main Window
/// </summary>
class MainViewModel
{
public ApplicationModel Model { get; set; }
public MainViewModel()
{
Model = new ApplicationModel();
Model.ListOfThingsToDo.Add("Clean the yard");
Model.ListOfThingsToDo.Add("Walk dog");
}
// Some method that will be called when you want to open another window
public void OpenTheWindow()
{
var modalViewModel = new NewTaskViewModel(Model);
// Create an instance of your new Window and show it.
var win = new NewTaskWindow(modalViewModel);
win.ShowDialog();
}
}
/// <summary>
/// Model to hold the data
/// </summary>
class ApplicationModel
{
public ObservableCollection<string> ListOfThingsToDo { get; set; }
public ApplicationModel()
{
ListOfThingsToDo = new ObservableCollection<string>();
}
}
/// <summary>
/// ViewModel to handle adding new things to do
/// </summary>
class NewTaskViewModel
{
public ApplicationModel Model { get; set; }
public NewTaskViewModel(ApplicationModel model)
{
Model = model;
}
// Add methods here that will be called to add tasks to the Model.ListOfThingsToDo
public void AddTask()
{
Model.ListOfThingsToDo.Add("the new task to do");
}
}