简体   繁体   English

在同一WPF ContextMenu MenuItem中声明的两个控件之间的绑定

[英]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 ? 为什么我不能在DataGrid的MenuItem中的两个元素之间绑定?

This is not binding between multiple MenuItems it relates to binding within items present in the header template of the same MenuItem. 这不是多个MenuItem之间的绑定,它与同一MenuItem的标题模板中存在的项目内的绑定有关。

This works fine when the same controls are hosted outside a DataGrid . 当在DataGrid外部托管相同的控件时,这可以很好地工作。 But in a MenuItem I get binding errors "Cannot find source for binding with reference...". 但是在MenuItem中,出现绑定错误“找不到引用的绑定源...”。 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. 请注意,这不是ContextMenu中MenuItemElementName Binding的重复项,因为绑定方案稍有不同,并且没有答案解决此问题。

<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>

You can use x:Reference to achieve it. 您可以使用x:Reference来实现。 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM