Hi,
I declare a simple contextmenu in XAML and try to accomplish a binding reference to another element in the same contextmenu. One time I try with ElementName and with RelativeSource/FindAncestor. Although the designer supports it, the runtime tells shows an error for both versions:
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.TextBox', AncestorLevel='1''. BindingExpression:Path=Text; DataItem=null; target element is 'Button' (Name='');
target property is 'CommandParameter' (type 'Object')
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'ElementName=MyTextBox'. BindingExpression:Path=Text; DataItem=null; target element is 'Button' (Name=''); target property is 'CommandParameter' (type 'Object')
Here is the XAML containing a Window including its ContextMenu:
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mo="clr-namespace:TestExtendedDataGrid.Models"
xmlns:vm="clr-namespace:TestExtendedDataGrid.ViewModels"
Title="MainWindow"
Width="525"
Height="350"><Window.Resources><ResourceDictionary><vm:PersonsOverview x:Key="PersonsVM" /></ResourceDictionary></Window.Resources><Window.DataContext><StaticResourceExtension ResourceKey="PersonsVM" /></Window.DataContext><DockPanel><DataGrid AutoGenerateColumns="False"
DockPanel.Dock="Top"
ItemsSource="{Binding Path=Persons}"><DataGrid.Resources><ContextMenu x:Key="CellContextMenu"><MenuItem Header="MenuItem1"><!-- This is the TextBox I want to bind the command parameter of the buttons to --><TextBox Name="MyTextBox"
Width="100" /><MenuItem><!-- CommandParameter binding fails --><Button Command="{Binding Path=ClickCommand}"
CommandParameter="{Binding Path=Text,
RelativeSource={RelativeSource FindAncestor,
AncestorType=TextBox,
AncestorLevel=1}}" /></MenuItem><!-- CommandParameter binding also fails --><Button Command="{Binding Path=ClickCommand}"
CommandParameter="{Binding Path=Text,
ElementName=MyTextBox}" /></MenuItem></ContextMenu></DataGrid.Resources><DataGrid.Style><Style TargetType="DataGrid"><Setter Property="ContextMenu" Value="{StaticResource CellContextMenu}" /></Style></DataGrid.Style><DataGrid.Columns><DataGridTextColumn Binding="{Binding Path=FirstName}" /></DataGrid.Columns></DataGrid></DockPanel></Window>I found a thread about a similar problem but did not get it:
http://stackoverflow.com/questions/1013558/elementname-binding-from-menuitem-in-contextmenu
Thank you!