【发布时间】:2020-01-17 19:45:09
【问题描述】:
上下文:
- 我的 MVVM 应用程序中的绑定属性出现问题。现在我做了一个小项目来测试这个案例。它只包括窗口、视图模型、模型、BindableObject(带有 INotifyProperyChanged 的抽象类)和命令类。所有类都在同一个命名空间中,datacontext 在视图中设置,模型和 vm 具有 INotifyProperyChanged,视图中的文本绑定到绑定到模型属性的 vm 属性。构造函数设置模型属性并影响视图模型和视图中的属性。
问题:
- 当我更改模型中的属性时,它不会更改视图模型和视图中的属性。
这里是 BaseModel 和 Command 类:
abstract class BindableObject : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertieChanged ([CallerMemberName]string name = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
class Command : ICommand
{
private Action<object> execute;
private Func<object, bool> canExecute;
public Command(Action<object> execute, Func<object, bool> canExecute = null)
{
this.execute = execute;
this.canExecute = canExecute;
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public bool CanExecute(object parameter)
{
return this.canExecute == null || this.canExecute(parameter);
}
public void Execute(object parameter)
{
this.execute(parameter);
}
}
型号:
public class Model : BindableObject
{
private int modelValue;
public int ModelValue { get => modelValue; set { modelValue = value; OnPropertieChanged(); } }
public Model ()
{
ModelValue = 111;
}
public void ChangeValue ()
{
ModelValue = 777;
}
}
视图模型:
class MainVM : BindableObject
{
private int myValue;
public int MyValue { get => myValue; set { myValue = value; OnPropertieChanged(); } }
public ICommand Command1 { get; set; }
public MainVM()
{
var model = new Model();
MyValue = model.ModelValue;
Command1 = new Command( (obj) => model.ChangeValue() );
}
}
查看:
<Window>
...
<Window.DataContext>
<local:MainVM/>
</Window.DataContext>
<StackPanel>
<TextBlock Text="{Binding MyValue}"/>
<Button Command="{Binding Command1}"/>
</StackPanel>
</Window>
【问题讨论】:
标签: c# wpf mvvm model viewmodel