簡體   English   中英

無法將命令綁定到Menu的頂級MenuItem

[英]Command binding to top-level MenuItem of Menu doesn't work

我正在學習WPF並開發一個動態Menu,該菜單由其ItemsSource到ObservableCollection數據綁定驅動。 為此,我有一個簡單的MenuItemViewModel和一個HierarchicalDataTemplate用於將MenuItems自動綁定到它。

我的問題是Command屬性對於頂級菜單項不起作用。 盡管已設置菜單項,但MenuItem不會在鼠標單擊時作出反應,並且如果無法執行Command,也不會被禁用。 簡直就像是沒有束縛。

但是對於較低級別的菜單項,它可以按預期工作。 我認為這應該是我的HierarchicalDataTemplate的問題,但我找不到它,因為正如我所看到的,模板中沒有代碼可能只影響頂層MenuItem的命令綁定。

MenuItemViewModel實現INotifyPropertyChanged並包含以下公共屬性:

string Text
Uri ImageSource
ICommand Command
ObservableCollection<MenuItemViewModel> Children

我的Window.Resources MenuItem的HierarchicalDataTemplate如下:

<HierarchicalDataTemplate DataType="{x:Type common:MenuItemViewModel}"
                          ItemsSource="{Binding Path=Children}">

    <HierarchicalDataTemplate.ItemContainerStyle>
        <Style TargetType="MenuItem">
            <Setter Property="Command"
                Value="{Binding Command}" />
        </Style>
    </HierarchicalDataTemplate.ItemContainerStyle>

    <StackPanel Orientation="Horizontal">
        <Image Source="{Binding ImageSource}" />
        <TextBlock Text="{Binding Text}" VerticalAlignment="Center"/>
    </StackPanel>

</HierarchicalDataTemplate>

你能指出我的錯誤嗎?

編輯:頂層MenuItem不包含任何子項(即,關聯的ViewModel的Children集合為空)。

感謝@sTrenat的評論,我在下面提出了解決方案。

<Menu.Resources>
    <!-- cancel sharing of image so Icon will work properly -->
    <Image x:Key="MenuIcon" Source="{Binding ImageSource}" x:Shared="False"/>
</Menu.Resources>

<Menu.ItemContainerStyle>
    <Style TargetType="{x:Type MenuItem}"
           BasedOn="{StaticResource {x:Type MenuItem}}">
        <Setter Property="Header" Value="{Binding Text}" />
        <Setter Property="Icon" Value="{StaticResource MenuIcon}"/>
        <Setter Property="Command" Value="{Binding Command}"/>
        <Setter Property="ItemsSource" Value="{Binding Children}" />

        <!-- centering MenuItem's Header -->
        <Setter Property="HeaderTemplate">
            <Setter.Value>
                <DataTemplate>
                    <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" Content="{Binding}" />
                </DataTemplate>
            </Setter.Value>
        </Setter>

        <!-- setting Icon to null when ImageSource isn't specified -->
        <Style.Triggers>
            <DataTrigger Binding="{Binding ImageSource}"
                        Value="{x:Null}">
                <Setter Property="Icon" Value="{x:Null}"/>
            </DataTrigger>
        </Style.Triggers>
    </Style>
</Menu.ItemContainerStyle>

暫無
暫無

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

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