我正在向現有的大型 WPF 客戶端應用程式添加一個具有功能的新按鈕。ButtonCommand應該通過DelegateCommand<T>. 問題是整個應用程式在啟動時崩潰,顯然是因為這個DelegateCommand<T>。我的代碼如下。
BaseFormViewModel(由 PensionTakerViewModel 繼承)
public DelegateCommand<DocumentType> AddFileCommand { get; private set; }
public BaseFormViewModel(...)
{
this.AddFileCommand = new DelegateCommand<DocumentType>(this.ExecuteAddFileCommand);
}
protected virtual void ExecuteAddFileCommand(DocumentType documentType)
{
// Do something...
}
PensionTakerView
<ctrl:ErrorDecorator Grid.Row="1" Grid.Column="0">
<ComboBox AutomationProperties.AutomationId="cmbDocumentType"
ItemsSource="{Binding ViewModel.DocumentTypes, ElementName=Root}"
DisplayMemberPath="Name"
SelectedValuePath="Value"
SelectedValue="{Binding DocumentType}"/>
</ctrl:ErrorDecorator>
<Button Grid.Row="1" Grid.Column="2" Content="Tilf?j fil"
Command="{Binding ViewModel.AddFileCommand, ElementName=Root}"
CommandParameter="{Binding DocumentType}"/>
現在應用程式在啟動時崩潰了,堆疊跟蹤的有趣部分如下(我有匿名的客戶名稱和術語)。對不起,小尺寸的影像。

I am quite new to both WPF and MVVM, so it's a bit of a learning curve for me. But from what I understand, it is complaining about the second parameter of the DelegateCommand<T> which is the CanExecute method. But DelegateCommand<T> also has a constructor which only takes one parameter - the Execute method. So why is it complaining over this?
I have tried also passing in a CanExecute method which just returns true. But the application is still crashing with the same error.
This same use of DelegateCommand<T> is existing several places in the application with the same syntax and signature with no problems. So this really shouldn't be an issue.
I have also tried using an ICommand and having the ExecuteAddFileCommand without parameters. This works for me, but is obviously not a solution as I need to pass a DocumentType.
有人可以幫助我進一步解決問題嗎?
uj5u.com熱心網友回復:
我懷疑命令引數不是DocumentType物件。
如果您將命令的型別更改為DelegateCommand<object>您應該避免出現例外。
然后你可以在你的ExecuteAddFileCommand方法中放置一個斷點來確定引數的實際型別以及它是否已經被設定。如果沒有,請檢查您DocumentType系結到的源屬性CommandParameter:
CommandParameter="{Binding DocumentType}"
它的型別必須與DelegateCommand<T>.
uj5u.com熱心網友回復:
因此,我今天進一步研究了這一點,并采用了 @mm8 的理論,即 myCommandParameter不是 type DocumentType。所以我一直跟蹤DocumentType,發現有些地方可以為空,而有些地方則不能。一旦我將我的更改CommandParameter為 type DocumentType?,應用程式就會停止崩潰。我的傳入引數ExecuteAddFileCommand()仍然null是。那當然是因為我必須在DelegateCommand<T>. 所以作業代碼看起來像這樣。
BaseFormViewModel(由 PensionTakerViewModel 繼承)
public DelegateCommand<DocumentType?> AddFileCommand { get; private set; }
public BaseFormViewModel(...)
{
this.AddFileCommand = new DelegateCommand<DocumentType?>(param => this.ExecuteAddFileCommand(param));
}
protected virtual void ExecuteAddFileCommand(DocumentType? documentType)
{
// Do something...
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/448347.html
