Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 相对于按钮放置上下文菜单_C#_Wpf_Xaml_Mvvm - Fatal编程技术网

C# 相对于按钮放置上下文菜单

C# 相对于按钮放置上下文菜单,c#,wpf,xaml,mvvm,C#,Wpf,Xaml,Mvvm,我正试图做描述的事情,除了用一个矩形代替一个按钮。我做了答案中描述的事情(还有很多其他事情),但我无法让它显示为相对于矩形的显示(在我的例子中,矩形是由按钮使用的) 我使用矩形作为按钮,因为我不喜欢按钮的鼠标悬停效果,而且只使用矩形似乎比构建自定义按钮更容易。值得注意的是,在Expression Blend 4中,我甚至在使用按钮时也遇到了同样的问题 这是我的矩形的XAML: <Rectangle x:Name="rectangle" HorizontalAlignment

我正试图做描述的事情,除了用一个矩形代替一个按钮。我做了答案中描述的事情(还有很多其他事情),但我无法让它显示为相对于矩形的显示(在我的例子中,矩形是由按钮使用的)

我使用矩形作为按钮,因为我不喜欢按钮的鼠标悬停效果,而且只使用矩形似乎比构建自定义按钮更容易。值得注意的是,在Expression Blend 4中,我甚至在使用按钮时也遇到了同样的问题

这是我的矩形的XAML:

        <Rectangle x:Name="rectangle" HorizontalAlignment="Left" MouseDown="MenuClicked" Height="55" VerticalAlignment="Top" Width="135" Grid.ColumnSpan="2" Margin="0,1,0,0" ContextMenuService.Placement="Bottom">
        <Rectangle.ContextMenu>
            <ContextMenu x:Name="Menu" >

                <MenuItem x:Name="LoadXML" Header="Load XML" Command="{Binding Command}" CommandParameter="BrowseXML"/>
                <MenuItem x:Name="SaveXML" Header="Save XML" Command="{Binding Command}" CommandParameter="SaveXML"/>
                <MenuItem x:Name="SaveBinary" Header="Save Binary" Command="{Binding Command}" CommandParameter="SaveBinary"/>
                <MenuItem x:Name="SaveText" Header="Save Text" Command="{Binding Command}" CommandParameter="SaveText"/>
            </ContextMenu>
        </Rectangle.ContextMenu>

        <Rectangle.Fill>
            <ImageBrush ImageSource="Resources/Logo.png" Stretch="Uniform" />
        </Rectangle.Fill>

    </Rectangle>

您需要设置
ContextMenuService.PlacementTarget
属性,以便框架知道上下文菜单应该相对于哪个元素定位,例如:

<Rectangle x:Name="rectangle" ContextMenuService.PlacementTarget="{Binding RelativeSource={RelativeSource Self}}" ... />

只需将该属性添加到矩形声明中。当与
ContextMenuService.Placement=“Bottom”
组合使用时,上下文菜单将按您的预期显示在底部


编辑:由于您以编程方式打开菜单,因此需要直接在菜单本身上设置
放置
放置目标
属性。当在菜单所有者上设置时,
ContextMenuService
中的附加属性仅在通过常规方式(例如,右键单击)打开上下文菜单时生效。在MouseDown处理程序中,设置
PlacementTarget=this,但您应该设置
PlacementTarget=rectangle

我这样做了,所以我的矩形声明现在看起来是这样的:它仍然出现在单击点处:[您是以编程方式打开菜单还是仅通过右键单击矩形打开菜单?嗯,我也使用MouseDown命令来启用矩形的左键单击。这就是导致问题的原因吗?我会将使用的例程添加到OP中。每当我尝试在实际矩形中使用PlacementTarget时,我都会得到一个“UIElement”的TypeConverter不支持从字符串“错误”转换。我当前的确切文本是PlacementTarget=“矩形”,但它似乎一点也不喜欢PlacementTarget。有什么想法吗?顺便说一句,非常感谢您迄今为止的帮助。您可以在C#事件处理程序中设置它,也可以尝试将其设置为
{Binding ElementName=rectangle}
,但由于Xaml名称范围中的特殊性,这可能不起作用。
<Rectangle x:Name="rectangle" ContextMenuService.PlacementTarget="{Binding RelativeSource={RelativeSource Self}}" ... />