我想在contextMenu中的updown控件和称为" fileexplorerControl"的自定义控件之间创建绑定(但可以在任何控件上进行仿真...)。当我运行程序时,一个打开的上下文菜单,Updown是空的,当我将任何数字放置时,会发生任何效果。问题在哪里?/
<view:FileExplorerControl Grid.Column="0"
Padding="5"
x:Name="LeftFileExplorer"
DataContext=
"{Binding LeftFileExplorerViewModel}">
<view:FileExplorerControl.ContextMenu>
<ContextMenu>
<StackPanel>
<TextBlock>Font Size</TextBlock>
<xctk:IntegerUpDown Value="{Binding
ElementName=LeftFileExplorer,
Path=FontSize, Mode=TwoWay}"
Minimum="8"
Maximum="32"/>
</StackPanel>
</ContextMenu>
</view:FileExplorerControl.ContextMenu>
</view:FileExplorerControl>
调试窗口中的错误消息:
system.windows.data错误:4:找不到使用参考'elementName = leftfileExplorer''的源。bindingexpression:path = fontsize;dataitem = null;目标元素是'IntegerupDown'(name ='');目标属性为" value"(类型为'nullable'1')
您的问题是上下文菜单不在主要的视觉树中,因此ElementName
无法正常工作。上下文菜单本身是一个小的,无父的,无源的视觉树。
您指向视觉树的链接是ContextMenu
的PlacementTarget
属性。菜单弹出时,PlacementTarget
将是拥有上下文菜单的控件。在这种情况下,这是view:FileExplorerControl
。方便地,这就是您想要的。
因此,请使用RelativeSource
获取ContextMenu
,然后使用其PlacementTarget
属性获取FileExplorerControl
。
<xctk:IntegerUpDown
Value="{Binding PlacementTarget.FontSize, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
/>