如何将ContextMenu添加到Button

时间:2013-12-26 05:31:25

标签: xaml windows-phone-7 button windows-phone-8 contextmenu

我有一个几个按钮的StackPanel,主题看起来像瓷砖。每个都可以固定到“开始”屏幕。我想为每个添加一个ContextMenu来启用此功能。我怎么能这样做?另外,如何确定点按的项目?

MainPage.xaml中

<StackPanel HorizontalAlignment="Left" Orientation="Horizontal">

                        <Button x:Name="Tile1" Height="173" Width="173" Margin="12,0,0,0" Click="1_Click" Style="{StaticResource ButtonStyle1}" toolkit:TiltEffect.IsTiltEnabled="True">
                            <Button.Content>
                                <Image Source="/Assets/Tiles/1.png"/>
                            </Button.Content>
                        </Button>
                        <Button x:Name="Tile2" Height="173" Width="173" Margin="12,0,0,0" Click="2_Click" Style="{StaticResource ButtonStyle1}" toolkit:TiltEffect.IsTiltEnabled="True">
                            <Button.Content>
                                <Image Source="/Assets/Tiles/2.png"/>
                            </Button.Content>
                        </Button>
                        <Button x:Name="Tile3" Height="173" Width="173" Margin="12,0,0,0" Click="3_Click" Style="{StaticResource ButtonStyle1}" toolkit:TiltEffect.IsTiltEnabled="True">
                            <Button.Content>
                                <Image Source="/Assets/Tiles/3.png"/>
                            </Button.Content>
                        </Button>
</StackPanel>

1 个答案:

答案 0 :(得分:0)

由于您手动创建了这些按钮 - 我的意思不是generated using DataTemplate左右 - 您需要手动为每个按钮添加ContextMenu。

...
<Button x:Name="Tile1" Height="173" Width="173" Margin="12,0,0,0" toolkit:TiltEffect.IsTiltEnabled="True">
    <Button.Content>
        <Image Source="/Assets/Tiles/IconicTileSmall.png"/>
    </Button.Content>
    <toolkit:ContextMenuService.ContextMenu>
        <toolkit:ContextMenu>
            <toolkit:MenuItem Header="Pin To Start" Click="MenuItem_Click"/>
        </toolkit:ContextMenu>
    </toolkit:ContextMenuService.ContextMenu>
</Button>
<Button x:Name="Tile2" Height="173" Width="173" Margin="12,0,0,0" toolkit:TiltEffect.IsTiltEnabled="True">
    <Button.Content>
        <Image Source="/Assets/Tiles/IconicTileSmall.png"/>
    </Button.Content>
    <toolkit:ContextMenuService.ContextMenu>
        <toolkit:ContextMenu>
            <toolkit:MenuItem Header="Pin To Start" Click="MenuItem_Click"/>
        </toolkit:ContextMenu>
    </toolkit:ContextMenuService.ContextMenu>
</Button>
...

但至少,有一种方法可以重用处理MenuItem点击事件的方法:

private void MenuItem_Click(object sender, RoutedEventArgs e)
{
    var menuItem = (MenuItem) sender;
    var ctxMenu = (ContextMenu) menuItem.Parent;
    var tileButton = (Button) ctxMenu.Owner;

    //Next: pin corresponding tileButton to start
}