【问题标题】:How to disable the ListView's context menu when nothing is selected?未选择任何内容时如何禁用 ListView 的上下文菜单?
【发布时间】:2012-03-03 23:55:24
【问题描述】:

我在 WPF 中有一个 ListView 设置为 GridView,它有一个上下文菜单。如何仅在 ListView 中选择某些内容时启用上下文菜单?

我想在 XAML 中执行所有这些操作以遵循 MVVM 模式,所以任何帮助都会很好。

【问题讨论】:

    标签: wpf mvvm contextmenu


    【解决方案1】:

    您应该使用触发器。首先将 ContextMenu 定义为资源。 这是一个简短的示例:

    <Window x:Class="SO.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    
        <Window.Resources>
            <ContextMenu x:Key="ctxmnu">
                <MenuItem Header="Open" />
                <MenuItem Header="Close" />
            </ContextMenu>
        </Window.Resources>
    
        <StackPanel>
            <ListView x:Name="lv">
                <ListView.Items>
                    <clr:String>Item 1</clr:String>
                    <clr:String>Item 2</clr:String>
                </ListView.Items>
                <ListView.View>
                    <GridView>
                        <GridViewColumn>
                            <GridViewColumn.CellTemplate>
                                <DataTemplate>
                                    <TextBlock Text="{Binding}" />
                                </DataTemplate>
                            </GridViewColumn.CellTemplate>
                        </GridViewColumn>
                    </GridView>
                </ListView.View>
                <ListView.Style>
                    <Style TargetType="ListView">
                        <Setter Property="ContextMenu" Value="{StaticResource ctxmnu1}" />
                        <Style.Triggers>
                            <Trigger Property="SelectedIndex" Value="-1">
                                <Setter Property="ContextMenu" Value="{x:Null}" />
                            </Trigger>
                        </Style.Triggers>
                    </Style>
                </ListView.Style>
            </ListView>
        </StackPanel>
    </Window>
    

    说了这么多,我无法想象你想要做的真实场景。首先,右键单击 ListView(弹出上下文菜单)将选择一个项目。第二 - 我认为这是一个糟糕的 UI 设计。最好显示相同的菜单,但禁用项目(您的情况下的所有项目)。这样,它会向用户提示存在弹出菜单,但其功能目前未启用。

    【讨论】:

    • 感谢您的帮助。我会将其调整为仅禁用项目^^
    猜你喜欢
    • 1970-01-01
    • 2017-12-05
    • 1970-01-01
    • 2013-06-17
    • 1970-01-01
    • 2016-09-27
    • 1970-01-01
    • 2021-03-17
    • 1970-01-01
    相关资源
    最近更新 更多