29 mars 2024

ContextMenu dans une ListBox avec DataTemplate

C’est peut être intéressant de partager cette solution qu’on m’a donnée à l’Hackaton Windows Phone/Azure de mars dernier, à savoir comment ajouter un ContextMenu à une ListBox.

Référence

Bien sur pour le ContextMenu, une référence au Microsoft.Phone.Controls.Toolkit est nécessaire ainsi que cette déclaration en entête de page XAML :

xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit" 
Code XAML
<ListBox x:Name="_ListBoxMesProjets">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <local:ItemProjet>
                <toolkit:ContextMenuService.ContextMenu>
                    <toolkit:ContextMenu>
                        <toolkit:MenuItem Header="Menu1" Click="MenuItem_Click" Foreground="Black"  />
                    </toolkit:ContextMenu>
                </toolkit:ContextMenuService.ContextMenu>
            </local:ItemProjet>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
code C#

Pour accèder à l’élèment sélectionné, on passe par le VisualTreeHelper :

private void MenuItem_Click(object sender, RoutedEventArgs e)
{
    var menuItem = sender as MenuItem;
    var fe = VisualTreeHelper.GetParent(menuItem) as FrameworkElement;

    Projet proj = fe.DataContext as Projet;
    (App.Current as App).MaListedeProjets.Remove(proj);
}
Localisation ?

En appliquant l’article de Pierre Cauchois sur l’internationalisation de notre application, il suffit de modifier la ligne 7 :

<toolkit:MenuItem Header="{Binding Path=LocResources.MainSubMenu1, Source={StaticResource LocalizedStrings}}"
                                                              Click="MenuItem_Click" Foreground="Black"  />
Attention au thème

Ce matin j’ai reçu un email de Windows Phone MarketPlace Certification :

Dear Windows Phone Marketplace Developer,

It has been determined through certification testing that the application indicated in the subject line has the following problem(s):

5.5.2
Pass with Notes: When the device’s theme is set to light, the textual content of the application cannot be seen.

Steps to Reproduce:
1. Set the device’s theme to light.
2. Launch the application.
3. Navigate to the « my project » pane on the panoramic.
4. Select and hold any project to reveal the context menu.
5. Observe the application’s content cannot be seen.

The application passes certification, however the reported issues need to be resolved in the next update to the application.

Alors si on fait pas gaffe comme moi, voici ce qui arrive sur un thème clair :

Selon le style, on peut forcer l’arrière plan/couleur police etc.. Moi j’ai forcé les couleurs de la ligne 6 :

<toolkit:ContextMenu Background="WhiteSmoke" BorderBrush="Black" BorderThickness="1.0" >