I am trying to bind to an element from a context menu inside a drop-down menu button (from http://shemesh.wordpress.com/2011/10/27/wpf-menubutton/). Even though outside the context menu the binding seems to work, the binding inside the context menu does not.
This is the XAML (very simplified):
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ScrollViewer Grid.Row="1" VerticalScrollBarVisibility="Auto" CanContentScroll="False">
<ListBox x:Name="lbScenarios" HorizontalContentAlignment="Stretch">
<ItemsControl.Template>
<ControlTemplate TargetType="ItemsControl">
<ItemsPresenter Width="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}, Path=ActualWidth}"/>
</ControlTemplate>
</ItemsControl.Template>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border>
<Expander>
<Expander.Header>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Margin="5,0,0,0" Grid.Column="0" VerticalAlignment="Center">Results</TextBlock>
<local:MenuButton Grid.Column="3" Content="Menu" Margin="5,0,0,0" VerticalAlignment="Center">
<local:MenuButton.Menu>
<ContextMenu>
<MenuItem Header="Save pie chart as image"
Command="{Binding SaveChartImageCommand}"
CommandParameter="{Binding ElementName=pieChart}" />
<MenuItem Header="Save bar chart as image"
Command="{Binding SaveChartImageCommand}"
CommandParameter="{Binding ElementName=barChart}" />
</ContextMenu>
</local:MenuButton.Menu>
</local:MenuButton>
</Grid>
</Expander.Header>
<Expander.Content>
<StackPanel>
<Image x:Name="pieChart" />
<Image x:Name="barChart" />
</StackPanel>
</Expander.Content>
</Expander>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ListBox>
</ScrollViewer>
</Grid>
</Window>
The binding that does not work is the {Binding ElementName=pieChart}, which is funny because the command is being found. I couldn't seem to get a RelativeSource to work, but can someone help me with getting the binding correct?