windows-phone-7 - 关闭 WP7 中数据绑定(bind)项目的上下文菜单

标签 windows-phone-7 contextmenu datatemplate

我的 WP7 中有一个列表框,它使用下面的 DataTemplete 来显示列表项

        <DataTemplate x:Key="MetaDataTemplate">
            <Grid Width="440" Margin="4,12,0,12">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="64"/>
                    <ColumnDefinition/>
                </Grid.ColumnDefinitions>
                <toolkit:ContextMenuService.ContextMenu>
                    <toolkit:ContextMenu>
                        <toolkit:MenuItem Header="download" Visibility="{Binding DownloadVisible}" Command="{Binding Download}"/>
                        <toolkit:MenuItem Header="get link" Command="{Binding GetLink}"/>
                        <toolkit:MenuItem Header="delete" Command="{Binding Delete}"/>
                    </toolkit:ContextMenu>
                </toolkit:ContextMenuService.ContextMenu>                    
                <Image Height="64" Width="64" Source="{Binding Thumb}" Stretch="UniformToFill"  />
                <TextBlock Text="{Binding MetaData.Name, Mode=OneWay}" VerticalAlignment="Center" Margin="12,0,0,0" 
                           Style="{StaticResource MetaDataHeaderStyle}" Grid.Column="1" />
            </Grid>
        </DataTemplate>

定义上下文菜单数据模板使得按下后退按钮时完全不可能关闭菜单!有人遇到这个问题吗?你是怎么解决的?

我在网上搜索了解决方案,但没有找到。如有任何帮助,我们将不胜感激。

最佳答案

一种方法是在后面的代码中添加一个 ContextMenu 变量,并在模板中为 ContextMenu 的 Opened 事件提供一个事件处理程序。

<toolkit:ContextMenuService.ContextMenu>
                        <toolkit:ContextMenu Opened="ContextMenu_Opened">
                            <toolkit:MenuItem Header="stuff">

                            </toolkit:MenuItem>
                            <toolkit:MenuItem Header="more stuff">

                            </toolkit:MenuItem>
                        </toolkit:ContextMenu>
                    </toolkit:ContextMenuService.ContextMenu>

Opened 事件处理程序中,将 ContextMenu 变量设置为该实例(即发送者)。

private void ContextMenu_Opened(object sender, RoutedEventArgs e)
    {
        menu = sender as ContextMenu;
    }

最后,重写OnBackKeyPress,这样如果变量不为null,并且菜单打开,则关闭菜单并取消后退事件。

protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
    {
        if (menu != null && menu.IsOpen)
        {
            menu.IsOpen = false;
            e.Cancel = true;
        }

        base.OnBackKeyPress(e);

    }

应该可以了!如果您有任何问题,或者需要我粘贴完整的代码,请告诉我。

关于windows-phone-7 - 关闭 WP7 中数据绑定(bind)项目的上下文菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10618125/

相关文章:

javascript - Jquery上下文菜单调用函数

c# - 临时更改属性

wpf - 如何将 ViewModel 的 ObservableCollection 绑定(bind)到 MenuItem?

silverlight - Windows Phone简单数据绑定(bind)问题

xaml - 如何在 Windows Phone 7 中将一个 XAML 包含到另一个 XAML 中?

silverlight - VS2010 for Windows Phone 7 & Blend 崩溃与 Mvvm-Light

silverlight - Windows Phone 7.1 可以更改外壳磁贴上的字体大小吗?

c# - 加入上下文菜单

c# - 如何将命令绑定(bind)到祖先数据上下文? WPF::MVVM

wpf - 根据 Silverlight/WPF 中绑定(bind)数据的值切换数据模板