I’ve got a WrapPanel from the Silverlight Toolkit in a WP7 application. In my codebehind I add my own usercontrols to this wrappanel. Each usercontrol is a square that displays information about a flight.
<ScrollViewer x:Name="MyScrollViewer" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto" Height="307" VerticalAlignment="Bottom">
<toolkit:WrapPanel x:Name="MonitoredWrapPanel" Margin="10,0,0,0" MinWidth="200" Width="{Binding ElementName=MyScrollViewer, Path=ViewportWidth}">
<toolkit:ContextMenuService.ContextMenu>
<toolkit:ContextMenu x:Name="FlightContextMenuInGrid">
<toolkit:MenuItem Header="Stop monitoring flight" Click="MenuItem_Click" Tag="{Binding Path=FlightId}" />
</toolkit:ContextMenu>
</toolkit:ContextMenuService.ContextMenu>
</toolkit:WrapPanel>
</ScrollViewer>
And the codebehind;
foreach (var flight in Cache.MonitoredCombinedFlights)
{
FlightSquare square = new FlightSquare();
square.DataContext = flight;
square.Margin = new Thickness(10, 5, 10, 5);
this.MonitoredWrapPanel.Children.Add(square);
}
My problem is that the MenuItem (for the ContextMenu) doesn’t bind to the FlightId property of the DataContext for my User Control, instead it just binds to itself.
How can I get the MenuItem to understand which FlightSquare it is on?
Apparently the
ContextMenuhas a differentDataContext. Binding in each square has nothing to do with theWrapPanelhere and you will have to manually set the binding object for theContextMenuin the code-behind.So to say, here is a snippet that shows how you can bind to a property in code-behind (exactly what you need to do):
That being said, there is one more problem in your case. The
ContextMenuis inside aWrapPanel– it is tied to it and not to the square. Therefore, you might change the way you are using theContextMenuto be inside the square instance rather than the common container.