问题
I have a StackPanel of a few buttons, which are themed to look like tiles. Each will have the ability to be pinned to the Start screen. I would like to add a ContextMenu to each to enable this functionality. How might I do this? Also, how do I determine the tapped item?
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:
Since you created those Button's manually -I mean not generated using DataTemplate or so-, you need to add ContextMenu for each of them manually too.
...
<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>
...
But at least, there is a way to reuse method that handle MenuItem's click event:
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
}
来源:https://stackoverflow.com/questions/20779621/how-to-add-contextmenu-to-button