【问题标题】:WPF binding to font size of other controller [duplicate]WPF绑定到其他控制器的字体大小[重复]
【发布时间】:2017-11-28 14:55:03
【问题描述】:

我想在上下文菜单中的 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”进行绑定的源。绑定表达式:路径=字体大小;数据项=空;目标元素是'IntegerUpDown'(名称='');目标属性为“值”(类型为“Nullable`1”)

【问题讨论】:

  • System.Windows.Data 错误:4:找不到与引用“ElementName=LeftFileExplorer”进行绑定的源。绑定表达式:路径=字体大小;数据项=空;目标元素是'IntegerUpDown'(名称='');目标属性是“值”(类型“Nullable`1”)

标签: c# wpf binding contextmenu


【解决方案1】:

您的问题是上下文菜单不在主视觉树中,因此ElementName 不起作用。上下文菜单本身就是一个小的、无父的、无实体的可视化树。

您到可视化树的链接是ContextMenuPlacementTarget 属性。当菜单弹出时,PlacementTarget 将是拥有上下文菜单的控件。在这种情况下,就是view:FileExplorerControl。方便的是,这就是您想要的。

所以使用RelativeSource 获取ContextMenu,然后使用其PlacementTarget 属性获取FileExplorerControl

<xctk:IntegerUpDown
    Value="{Binding PlacementTarget.FontSize, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
    />

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-22
    • 1970-01-01
    • 2016-01-11
    • 1970-01-01
    相关资源
    最近更新 更多