ã¯ããã«
ããMVVMãã¿ã¼ã³ã§ã¢ããªã±ã¼ã·ã§ã³ãå®è£ ããã®ã¯é¢åã ã
ããããªæãç°¡åã«å©ç¨ã§ããã¦ã¼ãã£ãªãã£ãç°¡åãªãã¼ã«ãããã®ä½¿ç¨ãæ¤è¨ãã¦ã¿ã¦ã¯ã©ãã§ãããããä»åã¯ãSilverlight 4ã®éçºã§å©ç¨ã§ããã¦ã¼ãã£ãªãã£ããã¼ã«ãããã解説ãã¾ãã
RelayCommand
ãICommandã¤ã³ã¿ã¼ãã§ã¤ã¹ã®å®è£ ãè¡ã£ã¦ããã¨ãExecuteã¡ã½ãããCanExecuteã¡ã½ãã以å¤ã¯ã»ã¼åããããªå®è£ ãè¡ãã°è¯ããã¨ã«æ°ã¥ãã¾ããMVVMãæ¡ç¨ããå¤ãã®ããã¸ã§ã¯ãã§ã¯ãExecuteã¡ã½ãããCanExecuteã¡ã½ãããããªã²ã¼ãã§åãåãããã«ããRelayCommandã¨ããã¦ã¼ãã£ãªãã£ã¯ã©ã¹ãå°å ¥ãã¦ãã³ãã³ãå®è£ ã®æéãä¿®æ£ãç°¡ç´ åãã¦ãã¾ãããªã¹ã1ã«RelayCommandã®ãµã³ãã«ã示ãã¾ãã
public class RelayCommand<T> : ICommand { private readonly Action<T> _execute; private readonly Func<bool> _canExecute; /// <summary> /// RelayCommandã®ã³ã³ã¹ãã©ã¯ã¿ã¼<br /> /// å¼æ°ã«ExecuteãCanExecuteã®å®ä½ãããªã²ã¼ãã§åãåã /// </summary> public RelayCommand(Action<T> execute) : this(execute, null) { } public RelayCommand(Action<T> execute, Func<bool> canExecute) { if (execute == null) throw new ArgumentNullException("execute"); _execute = execute; _canExecute = canExecute; } public event EventHandler CanExecuteChanged; public void RaiseCanExecuteChanged() { var handler = CanExecuteChanged; if (handler != null) { handler(this, EventArgs.Empty); } } // Executeã¡ã½ãããCanExecuteã¡ã½ããã§ã¯åãåã£ãExecuteãCanExecuteããªã²ã¼ããå®è¡ããã ã public void Execute(object parameter) { _execute((T)parameter); } public bool CanExecute(object parameter) { return _canExecute == null ? true : _canExecute(); } }
ããã¥ã¼ã¢ãã«å´ã§ã¯ãªã¹ã2ã®ããã«ãRelayCommandãå©ç¨ãã¾ãã
private RelayCommand<MainPageViewModel> _æ¤ç´¢Command; /// <summary> /// æ¤ç´¢ã³ãã³ããå ¬éããããããã£ã§ãã /// </summary> public RelayCommand<MainPageViewModel> æ¤ç´¢Command { get { if (_æ¤ç´¢Command == null) _æ¤ç´¢Command = new RelayCommand<MainPageViewModel>(æ¤ç´¢); return _æ¤ç´¢Command; } } /// <summary> /// æ¤ç´¢ã³ãã³ãã®æ¬ä½ã§ãã /// </summary> public void æ¤ç´¢(MainPageViewModel item) { var proxy = new æ¸ç±ç®¡çServiceProxy.æ¸ç±ç®¡çServiceClient(); proxy.Findæ¸ç±ByIdCompleted += (source, e) => { if (e.Error != null) MessageBox.Show(e.Error.Message); Id = e.Result.Id; ã¿ã¤ãã« = e.Result.ã¿ã¤ãã«; ç»é²æ¥ = e.Result.ç»é²æ¥; ISBN = e.Result.ISBN; TimeStamp = e.Result.TimeStamp; }; int id; if (! int.TryParse(item.SearchId, out id)) return; proxy.Findæ¸ç±ByIdAsync(id); }
ãååã®é£è¼ã®ãªã¹ã3ã§ç¤ºããã³ã¼ãã®Executeã¡ã½ããããã¥ã¼ã¢ãã«å´ã®æ¤ç´¢ã¡ã½ããã«ç§»åããRelayCommandãã¤ã³ã¹ã¿ã³ã¹åããã¿ã¤ãã³ã°ã§RelayCommandã«ããªã²ã¼ãã¨ãã¦å¼ã渡ãã¦ãã¾ãã