Slugart
Slugart

Reputation: 4680

Binding between two controls declared in the same WPF ContextMenu MenuItem

Why can't I bind between two elements which are in a MenuItem within a DataGrid?

This is not binding between multiple MenuItems it relates to binding within items present in the header template of the same MenuItem.

This works fine when the same controls are hosted outside a DataGrid. But in a MenuItem I get binding errors "Cannot find source for binding with reference...". Surely they are in the same visual tree and can reference each other?

Note that this is not a duplicate of ElementName Binding from MenuItem in ContextMenu because the binding scenario is slightly different and none of the answers address this issue.

<DataGrid.ContextMenu>
    <ContextMenu>
        <MenuItem  >
            <MenuItem.Header>
                <StackPanel Orientation="Horizontal">
                    <ComboBox Margin="5 0" Name="comboBox">
                        <ComboBoxItem>1</ComboBoxItem>
                        <ComboBoxItem>2</ComboBoxItem>
                        <ComboBoxItem>3</ComboBoxItem>
                    </ComboBox>
                    <TextBlock Margin="5 0" Text="{Binding ElementName=comboBox, Path=SelectedValue}"></TextBlock>
                </StackPanel>
            </MenuItem.Header>
        </MenuItem>
    </ContextMenu>
</DataGrid.ContextMenu>

Upvotes: 1

Views: 942

Answers (1)

Ayyappan Subramanian
Ayyappan Subramanian

Reputation: 5366

You can use x:Reference to achieve it. Refer below code.

<DataGrid.ContextMenu>
            <ContextMenu>
                <MenuItem  >
                    <MenuItem.Header>
                        <StackPanel Orientation="Horizontal">
                            <ComboBox Margin="5 0" x:Name="comboBox">
                                <ComboBoxItem>1</ComboBoxItem>
                                <ComboBoxItem>2</ComboBoxItem>
                                <ComboBoxItem>3</ComboBoxItem>
                            </ComboBox>
                            <TextBlock Margin="5 0" 
                                       Text="{Binding Source={x:Reference comboBox}, 
                                       Path=Text}">
                           </TextBlock>
                        </StackPanel>
                    </MenuItem.Header>
                </MenuItem>
            </ContextMenu>
        </DataGrid.ContextMenu>

Upvotes: 2

Related Questions