I am trying to make a context fold out menu on a list box component, it has a simple but i can’t manage to get the binding for command paramter to work.
Here is a simplified view of my user control XAML.
<?xml version="1.0" encoding="utf-8"?>
<UserControl x:Name="userControl"
x:Class="SampleControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:SampleUWP"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:inter="microsoft"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DataContext="{d:DesignInstance Type=local:ViewModel}">
<Grid>
<ListBox x:Name="myList" ItemsSource="{Binding ListSource}" DisplayMemberPath="Name">
<ListBox.ContextFlyout>
<MenuFlyout>
<MenuFlyoutItem Text="Add" Command="{Binding Add}"/>
<MenuFlyoutItem Text="Remove" Command="{Binding Remove}" CommandParameter="{Binding SelectedItem, ElementName=myList}"/>
</MenuFlyout>
</ListBox.ContextFlyout>
</ListBox>
</Grid>
</UserControl>
A simple representation of a ViewModel.
public class ViewModel
{
public ICommand Add {get;} // Ignored for now
public ICommand Remove {get;} = new DelegatedCommand(OnRemove, CanRemove)
public IEnumerable<Item> ItemSource {get;} = new [] {
new Item { Id = 1, Name = "First" },
new Item { Id = 2, Name = "Second" }
}
private bool CanRemove(object param)
{
// We want param to be the list item so we can get the Id
}
private OnRemove(object obj)
{
// Do some logic for removing
}
}
public class Item
{
public int Id {get;set;}
public string Name {get;set;}
}
I have tried finding a solution on this on forums but nothing i tried has worked, the closest i have come is to get the MenuFlyoutItem with {Binding RelativeSource={RelativeSource Mode=Self}}
but i don’t know a way to get my list box from here either.
I understand that the context menu it self is in a different visual tree just like in WPF but there i could get the source by using relative source and using find ancestor but in UWP i cannot seam to find a solution on how to bind my command parameter to the list item so i can send it as a paramter.
One note to mention is that there is no problem with the command, it resolves to the ViewModel without issues, but the command parameter i cannot figure out.