Windows Phone - ListBox with Tiles and ContextMenu

2019-09-14 02:42发布

问题:

I have a ListBox (binds to an observable collection) and each item is displayed as tile. The style for the ListBoxItems is defined in my App.xaml and linked with the property ItemContainerStyle. I want to display a ContextMenu for each tile with one MenuItem "Pin to Start". This does work, but the MenuItem is still enabled although I bind the IsEnabled property to ViewModel property which returns false. If I set the IsEnabled property to false in my XAML code (without binding), I have the same problem the MenuItem is enabled.

App.xaml

<Style x:Key="TileListBoxItemStyle" TargetType="ListBoxItem">
    <Setter Property="Padding" Value="0"/>
    <Setter Property="Margin" Value="12,12,0,0"/>
    <Setter Property="Background" Value="{StaticResource PhoneAccentBrush}"/>
    <Setter Property="Foreground" Value="White"/>
    <Setter Property="Width" Value="210"/>
    <Setter Property="Height" Value="210"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="ListBoxItem">
                <Border x:Name="LayoutRoot" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" HorizontalAlignment="{TemplateBinding HorizontalAlignment}" VerticalAlignment="{TemplateBinding VerticalAlignment}">
                    <ContentControl x:Name="ContentContainer" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" Foreground="{TemplateBinding Foreground}" HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"/>
                    <toolkit:ContextMenuService.ContextMenu>
                        <toolkit:ContextMenu>
                            <toolkit:MenuItem 
                                Header="Pin to Start"
                                IsEnabled="{Binding IsNotPinned}"
                                Command="{Binding PinToStartCommand}" 
                                CommandParameter="{Binding}"/>
                        </toolkit:ContextMenu>
                    </toolkit:ContextMenuService.ContextMenu>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

VieModel property:

public bool IsNotPinned
{
    get
    {
        //return !TileManager.IsTileAvailable(this);
        return false;
    }
}

public ICommand PinToStartCommand { get; private set; }

private void PinToStart(Item item)
{
    //...
}