0

I want to create binding between UpDown control in contextmenu and custom control called "FileExplorerControl"(but it can be simulated on any control ... ). When I run the program a open context menu, UpDown is empty, when I put there any number, any effects occurs. Where is the problem ?/

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

Error message in debug window:

System.Windows.Data Error: 4 : Cannot find source for binding with reference 'ElementName=LeftFileExplorer'. BindingExpression:Path=FontSize; DataItem=null; target element is 'IntegerUpDown' (Name=''); target property is 'Value' (type 'Nullable`1')

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Josh Butter
  • 49
  • 1
  • 10
  • System.Windows.Data Error: 4 : Cannot find source for binding with reference 'ElementName=LeftFileExplorer'. BindingExpression:Path=FontSize; DataItem=null; target element is 'IntegerUpDown' (Name=''); target property is 'Value' (type 'Nullable`1') – Josh Butter Nov 28 '17 at 15:10

1 Answers1

0

Your problem is that the context menu is not in the main visual tree, so ElementName won't work. The context menu is a small, parentless, disembodied visual tree unto itself.

Your link to the visual tree is the PlacementTarget property of the ContextMenu. When the menu pops up, PlacementTarget will be the control that owns the context menu. In this case, that's view:FileExplorerControl. Conveniently, that's the one you want.

So use RelativeSource to get the ContextMenu, then use its PlacementTarget property to get the FileExplorerControl.

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