MVVM Prism WPF -设置公共属性和SetProperty
本文关键字:属性 SetProperty 设置 Prism WPF MVVM | 更新日期: 2023-09-27 18:11:20
我是MVVM和Prism的新手。我有下面的ViewModel
using System.Collections.Generic;
using BasicMVVMQuickstart_Desktop.Model;
using Microsoft.Practices.Prism.Mvvm;
namespace BasicMVVMQuickstart_Desktop.ViewModels
{
public class QuestionnaireViewModel : BindableBase
{
private Questionnaire questionnaire;
public QuestionnaireViewModel()
{
this.Questionnaire = new Questionnaire();
this.AllColors = new[] { "Red", "Blue", "Green" };
}
public Questionnaire Questionnaire
{
get { return this.questionnaire; }
set {
SetProperty(ref this.questionnaire, value);
}
}
public IEnumerable<string> AllColors { get; private set; }
}
}
我正试图从另一个视图模型设置问卷,并使用另一个视图模型的设定值更新WPF UI。但不幸的是,它不起作用。下面是另一个视图模型的代码。我在"私有void OnSubmit(object obj)"中设置了属性,但是当我运行应用程序并按下提交时,UI没有得到更新。有人知道这个工作还需要添加什么吗?如果我设置this。questionnaireviewmodel。questionnaire。Age = 32;" inside "public MainWindowViewModel()",然后UI在运行时更新,但与OnSubmit不工作。请帮助。
using System.Diagnostics;
using System.Text;
using System.Windows.Input;
using BasicMVVMQuickstart_Desktop.Model;
using Microsoft.Practices.Prism.Commands;
using Microsoft.Practices.Prism.Mvvm;
namespace BasicMVVMQuickstart_Desktop.ViewModels
{
public class MainWindowViewModel : BindableBase
{
public MainWindowViewModel()
{
this.SubmitCommand = new DelegateCommand<object>(this.OnSubmit);
this.QuestionnaireViewModel = new QuestionnaireViewModel();
this.ResetCommand = new DelegateCommand(this.OnReset);
}
public ICommand SubmitCommand { get; private set; }
public ICommand ResetCommand { get; private set; }
public QuestionnaireViewModel QuestionnaireViewModel { get; set; }
private void OnSubmit(object obj)
{
Debug.WriteLine(this.BuildResultString());
this.QuestionnaireViewModel.Questionnaire.Age = 32;
}
private void OnReset()
{
this.QuestionnaireViewModel.Questionnaire = new Questionnaire();
}
private string BuildResultString()
{
StringBuilder builder = new StringBuilder();
builder.Append("Name: ");
builder.Append(this.QuestionnaireViewModel.Questionnaire.Name);
builder.Append("'nAge: ");
builder.Append(this.QuestionnaireViewModel.Questionnaire.Age);
builder.Append("'nQuestion 1: ");
builder.Append(this.QuestionnaireViewModel.Questionnaire.Quest);
builder.Append("'nQuestion 2: ");
builder.Append(this.QuestionnaireViewModel.Questionnaire.FavoriteColor);
return builder.ToString();
}
}
}
当您在代码中更改Age属性时:
this.QuestionnaireViewModel.Questionnaire.Age = 32;
你改变了Questionnaire的属性,但没有改变QuestionnaireViewModel的属性。因此,您需要从BindableBase继承您的Questionnaire类,并为Age属性创建类似的代码:
private int _age;
public int Age
{
get { return _age; }
set { SetProperty(ref _age, value); }
}