我是 c# 的新手,正在尝试了解命令在 mvvm 架构中的工作方式。我需要做的是在单击按钮时更新一些信息。我认为我很好地实现了中继类,但根本没有更新。
RelayCommand.cs
public class RelayCommand : ICommand
{
private Action<object> execute;
private Func<object, bool> canExecute;
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public RelayCommand(Action<object> execute, Func<object, bool> canExecute)
{
this.execute = execute;
this.canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
return this.canExecute == null || this.canExecute(parameter);
}
public void Execute(object parameter)
{
this.execute(parameter);
}
}
MovieViewModel.cs
class MovieViewModel : INotifyPropertyChanged
{
Movie _movie;
private ICommand _updateCommand;
public event PropertyChangedEventHandler PropertyChanged;
public MovieViewModel()
{
_movie = new Movie
{
Title = "Unknown",
Genre = "Unknown",
Price = 11.0,
Score = 0
};
}
public Movie Movie
{
get
{
return _movie;
}
set
{
_movie = value;
}
}
public string Title
{
get
{
return Movie.Title;
}
set
{
Movie.Title = value;
RaisePropertyChanged("Title");
}
}
public string Genre
{
get
{
return Movie.Genre;
}
set
{
Movie.Genre = value;
RaisePropertyChanged("Genre");
}
}
public double Price
{
get
{
return Movie.Price;
}
set
{
Movie.Price = value;
RaisePropertyChanged("Price");
}
}
public double Score
{
get
{
return Movie.Score;
}
set
{
Movie.Score = value;
RaisePropertyChanged("Score");
}
}
private void RaisePropertyChanged(string name)
{
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
public ICommand UpdateCommand
{
get
{
if (_updateCommand == null)
{
_updateCommand = new RelayCommand(p => { updateMovie("ASD", "ZXC", 11.90, 0); }, p => true);
}
return _updateCommand;
}
set
{
_updateCommand = value;
}
}
public Movie updateMovie(string title, string genre, double price, double score)
{
_movie.Title = title;
_movie.Genre = genre;
_movie.Price = price;
_movie.Score = score;
return _movie;
}
}
按钮命令绑定(bind)
<Button x:Name="updateBtn" Content="Update" Grid.Column="1" Grid.Row="5" Width="75" Height="30" Command="{Binding UpdateCommand}"/>
最佳答案
尝试给予
RaisePropertyChanged("Movie");
感谢@Maverik 也给出了原因声明。您没有引发 PropertyChanged
事件,因为您绕过属性并直接访问基础字段。您应该像预期的那样使用虚拟机。
通过 VM 对模型的访问适用于您,就像它适用于 View 和其他绑定(bind)到您 VM 的客户端一样。
关于c# - Wpf中的中继命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37051966/