Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# ContextMenu CanExecute未更新_C#_Wpf_Contextmenu_Mvvm Light_Icommand - Fatal编程技术网

C# ContextMenu CanExecute未更新

C# ContextMenu CanExecute未更新,c#,wpf,contextmenu,mvvm-light,icommand,C#,Wpf,Contextmenu,Mvvm Light,Icommand,我对ContextMenu中菜单项的状态有问题。我有一批很好的汽车。汽车在一个列表框中可视化,对于每个列表框项目,我需要一个上下文菜单。在该上下文菜单中有一个选项ReserveCar 我遇到的问题是,Car的CanExecute仅在我右键单击任何一辆车时执行一次。当我右键单击另一辆汽车时,它们CanExecute将不再被调用 这导致当我右键单击一辆可以保留的汽车时,菜单项处于活动状态,但当我右键单击另一辆不能保留的汽车时,菜单项保持活动状态(因为CanExecute不会再次调用) 尝试将上下文菜

我对ContextMenu中菜单项的状态有问题。我有一批很好的汽车。汽车在一个列表框中可视化,对于每个列表框项目,我需要一个上下文菜单。在该上下文菜单中有一个选项ReserveCar

我遇到的问题是,
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>