[英]WPF : MenuItem.CommandParameter binding set to null
我為我的數據網格定義了以下 ContextMenu:
<igDP:XamDataGrid.ContextMenu>
<ContextMenu ItemsSource="{Binding CommandViewModels}" >
<ContextMenu.ItemContainerStyle>
<Style TargetType="MenuItem">
<Setter Property="Command" Value="{Binding Command}" />
<Setter Property="CommandParameter" Value="{Binding CommandParameter}" />
<Setter Property="Header" Value="{Binding Name}" />
<Setter Property="Icon" Value="{Binding Icon}" />
</Style>
</ContextMenu.ItemContainerStyle>
</ContextMenu>
</igDP:XamDataGrid.ContextMenu>
CommandViewModel 類定義如下:
public class CommandViewModel : ICommandViewModel
{
public CommandViewModel(string name, Image icon, ICommand command, object commandParameter = null, int index = 0)
{
Name = name;
Icon = icon;
Command = command;
CommandParameter = commandParameter;
Index = index;
}
public string Name { get; set; }
public Image Icon { get; set; }
public ICommand Command { get; set; }
public object CommandParameter { get; set; }
public int Index { get; set; }
}
當我右鍵單擊網格中的一行時,ContextMenu 的每個 MenuItem 的樣式都正確。 MenuItem 的圖標、標簽和命令符合預期。 但是,應該作為參數傳遞給綁定到 MenuItem.Command 的 RelayCommand 的命令參數 CommandViewModel.CommandParameter 為空。
我相當確定可用於綁定的命令參數不為空。 這是在 .NET 4.0 上運行的 WPF 應用程序。
有人經歷過嗎?
這顯然是 CommandParameter 綁定的一個已知問題。
由於我不想編輯 Prism 代碼,因此我最終使用了在引用的 CodePlex 帖子中定義的CommandParameterBehavior類。
修改我的自定義 RelayCommand 類以實現 IDelegateCommand,如下所示:
public class RelayCommand : IDelegateCommand
{
readonly protected Predicate<object> _canExecute;
readonly protected Action<object> _execute;
public RelayCommand(Predicate<object> canExecute, Action<object> execute)
{
_canExecute = canExecute;
_execute = execute;
}
public void RaiseCanExecuteChanged()
{
if (CanExecuteChanged != null)
CanExecuteChanged(this, EventArgs.Empty);
}
public virtual bool CanExecute(object parameter)
{
return _canExecute(parameter);
}
public event EventHandler CanExecuteChanged;
public virtual void Execute(object parameter)
{
_execute(parameter);
}
}
並修改我的原始樣式以使用 CommandParameterBehavior ,如下所示:
<Style TargetType="MenuItem">
<Setter Property="Command" Value="{Binding Command}" />
<Setter Property="CommandParameter" Value="{Binding CommandParameter}" />
<Setter Property="Header" Value="{Binding Name}" />
<Setter Property="Icon" Value="{Binding Icon}" />
<Setter Property="utility:CommandParameterBehavior.IsCommandRequeriedOnChange" Value="true"
</Style>
CommandParameter 現在已正確傳遞。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.