C# ContextMenu CanExecute未更新
我对ContextMenu中菜单项的状态有问题。我有一批很好的汽车。汽车在一个列表框中可视化,对于每个列表框项目,我需要一个上下文菜单。在该上下文菜单中有一个选项ReserveCar 我遇到的问题是,C# ContextMenu CanExecute未更新,c#,wpf,contextmenu,mvvm-light,icommand,C#,Wpf,Contextmenu,Mvvm Light,Icommand,我对ContextMenu中菜单项的状态有问题。我有一批很好的汽车。汽车在一个列表框中可视化,对于每个列表框项目,我需要一个上下文菜单。在该上下文菜单中有一个选项ReserveCar 我遇到的问题是,Car的CanExecute仅在我右键单击任何一辆车时执行一次。当我右键单击另一辆汽车时,它们CanExecute将不再被调用 这导致当我右键单击一辆可以保留的汽车时,菜单项处于活动状态,但当我右键单击另一辆不能保留的汽车时,菜单项保持活动状态(因为CanExecute不会再次调用) 尝试将上下文菜
Car
的CanExecute
仅在我右键单击任何一辆车时执行一次。当我右键单击另一辆汽车时,它们CanExecute
将不再被调用
这导致当我右键单击一辆可以保留的汽车时,菜单项
处于活动状态,但当我右键单击另一辆不能保留的汽车时,菜单项
保持活动状态(因为CanExecute
不会再次调用)
尝试将上下文菜单绑定到ListBoxItem
而不是ListBox
。由于ListBox
的上下文菜单绑定仅在第一次右键单击时发生,因此canexecute
不会在第一次右键单击后触发
<ListBox Name="simpleListBox"
ItemsSource="{Binding Cars}"
SelectedItem="{Binding SelectedCar}">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="ContextMenu">
<Setter.Value>
<ContextMenu>
...
</ContextMenu>
</Setter.Value>
</Setter>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
...
private RelayCommand<Car> _reserveCarCommand;
public ICommand ReserveCarCommand
{
get { return _reserveCarCommand ?? (_reserveCarCommand = new RelayCommanReserveCar, CanReserveCar)); }
}
public bool CanReserveCar(Car car)
{
return !car.IsReserved && ReservationsAreOpen;
}
public void ReserveCar(Car car)
{
car.IsReserved = true;
}
if (_reserveCarCommand != null) _reserveCarCommand .RaiseCanExecuteChanged();
<ListBox Name="simpleListBox"
ItemsSource="{Binding Cars}"
SelectedItem="{Binding SelectedCar}">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="ContextMenu">
<Setter.Value>
<ContextMenu>
...
</ContextMenu>
</Setter.Value>
</Setter>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>