我正在學習 WPF 和 MVVM 設計模式。目前,我的 ViewModel 中用于洗掉客戶命令的代碼如下所示:
public class vmCustomers : INotifyPropertyChanged
{
...
private ICommand _commandDeleteCustomer = null;
...
public ICommand CommandDeleteCustomer
{
get
{
if (_commandDeleteCustomer == null)
_commandDeleteCustomer = new RelayCommand<object>(DeleteCustomerAction, DeleteCustomerPredicate);
return _commandDeleteCustomer;
}
}
private void DeleteCustomerAction(object o)
{
...stuff...
}
private bool DeleteCustomerPredicate(object o)
{
...stuff...
return true;
}
}
我想將 ICommand 的宣告縮減為這樣的內容,以便我可以減少每個命令的編碼開銷:
public readonly ICommand CommandDeleteCustomer = new RelayCommand((obj) => DeleteCustomerAction(obj), (obj) => DeleteCustomerPredicate(obj));
但我得到這個錯誤:
A field initializer cannot reference the non-static field, method, or property vmCustomers.DeleteCustomerAction(object)
有沒有一種方法可以在一行代碼中宣告 ICommand,這樣我就可以簡單地關注與業務相關的代碼,而不是重復的基礎設施代碼。
uj5u.com熱心網友回復:
宣告一個只讀的自動實作屬性
public ICommand CommandDeleteCustomer { get; }
并將初始化陳述句移動到視圖模型建構式
public VmCustomers()
{
CommandDeleteCustomer = new RelayCommand(...);
}
uj5u.com熱心網友回復:
如果您RelayCommand.CanExecuteChanegd掛鉤CommandManager.RequerySuggested事件,您可以洗掉建構式初始化并在單行陳述句中將屬性初始化為只讀計算屬性:
// Creates a *new instance* on every Get() access
public ICommand CommandDeleteCustomer => new RelayCommand(...);
// The following is the verbose form of the previous single line property declaration:
public ICommand CommandDeleteCustomer
{
get => new RelayCommand(...);
}
要確保從屬性回傳相同的實體,請使用屬性初始化程式(單行陳述句):
// Returns the *same instance* on every Get() access.
// Note that you can't reference instance members like fields and properties from the initializer.
// This means the command delegates would have to be defined as 'private static'.
public ICommand CommandDeleteCustomer { get; } = new RelayCommand<object>(DeleteCustomerAction, DeleteCustomerPredicate);
private static void DeleteCustomerAction(object o)
{
...stuff...
}
private static bool DeleteCustomerPredicate(object o)
{
...stuff...
return true;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/532970.html
標籤:C#wpf虚拟机指令
上一篇:在ListView中顯示影像
