首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ContextMenu CanExecute未更新

ContextMenu CanExecute未更新
EN

Stack Overflow用户
提问于 2015-10-27 16:55:50
回答 1查看 598关注 0票数 1

我有一个关于ContextMenu中菜单项状态的问题。我有一个汽车的ObversableCollection。汽车在一个ListBox中可视化,对于每个我想要的ListBox项目,都有一个ContextMenu。在ContextMenu中有一个选项ReserveCar。

我遇到的问题是,当我右键单击任何汽车时,CarCanExecute只执行一次。在此之后,当我右键单击另一个CanExecute时,它们的Car将不再被调用。

这会导致当我右键单击一个可以保留的Car时,该MenuItem是活动的,但当我右键单击另一个我不应该保留的MenuItem时,该CanExecute仍然是活动的(因为不会再次调用CanExecute)。

代码语言:javascript
复制
<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:

代码语言:javascript
复制
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;
}

另外,当我在做一些事情时手动刷新命令时,CanExecute是用null作为参数调用的,所以这也不起作用。

代码语言:javascript
复制
if (_reserveCarCommand != null) _reserveCarCommand .RaiseCanExecuteChanged();
EN

回答 1

Stack Overflow用户

发布于 2015-10-27 18:00:20

尝试在ListBoxItem上而不是在ListBox上绑定上下文菜单。由于ListBox上下文菜单的绑定仅在第一次右击时发生,因此CanExectute不会在第一次右击后触发。

代码语言:javascript
复制
<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>
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33363479

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档