記錄一次WPF命令引數報錯,InvalidCastException: T for DelegateCommand<T> is not an object nor Nullable.

孤沉發表於2024-03-06

在使用WPF的時候對int或者bool型別進行繫結出現InvalidCastException: T for DelegateCommand is not an object nor Nullable.

 <Button Width="200" Height="30" Content="按鈕" Command="{Binding OpenCommand}" CommandParameter="{Binding Msg}"/>
 
  OpenCommand = new DelegateCommand<int/bool>(ExecuteOpen);

解決方案如下:
1、加上非空? ,以下是int型別寫法

 OpenCommand = new DelegateCommand<int?>(ExecuteOpen);

2、使用Nullable+泛型,下面是bool型別寫法

 OpenCommand = new DelegateCommand<Nullable<bool>>(ExecuteOpen);

相關文章