簡體   English   中英

ContextMenu CanExecute未更新

[英]ContextMenu CanExecute is not updated

我對ContextMenu中菜單項的狀態有疑問。 我有一個汽車的ObversableCollection。 對於每個我想要一個ContextMenu的ListBox項,這些汽車都在ListBox中可視化。 在該ContextMenu中,有一個ReserveCar選項。

他們遇到的問題是,當我右鍵單擊任何汽車時, CarCanExecute只能執行一次。 之后,當我右鍵單擊其他Car時,將不再調用它們的CanExecute

這導致當我右鍵單擊可以保留的Car時, MenuItem處於活動狀態,但是當我右鍵單擊另一個我不能保留的MenuItem ,其CanExecute保持活動狀態(因為不會再次調用CanExecute )。

<ListBox
    ItemsSource="{Binding Cars}"
    SelectedItem="{Binding SelectedCar}">
    <ListBox.ContextMenu>
        <ContextMenu>
            <MenuItem Header="Reserve Car" 
                        CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=ContextMenu}, Path=PlacementTarget.SelectedItem}"
                        Command="{Binding ReserveCarCommand}">
                <MenuItem.Icon>
                    <Image Source="{StaticResource ReserveCarIcon}" Width="24" Height="24"/>
                </MenuItem.Icon>
            </MenuItem>
        </ContextMenu>
    </ListBox.ContextMenu>
</ListBox>

我的ViewModel:

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;
}

另外,當我在做某事時手動刷新Command時, CanExecute會以null作為參數調用,因此也不起作用。

if (_reserveCarCommand != null) _reserveCarCommand .RaiseCanExecuteChanged();

嘗試將上下文菜單綁定到ListBoxItem而不是ListBox 由於綁定ListBox的上下文菜單僅在第一次單擊鼠標右鍵時發生,因此CanExectute在第一次右鍵單擊后不會觸發。

<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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM