1

我正在尝试将 ContextMenu 置于按钮下方。我正在尝试根据 ContextMenu 的高度设置 VerticalOffset 属性,以便无论项目数量如何,菜单的顶部始终位于同一位置。我似乎无法获得菜单的高度(可能是因为它还没有被绘制?)。我的代码在下面,如何获取 ContextMenu 的高度?

private void Button_Click(object sender, RoutedEventArgs e)
{
    Button PopUpButton = (sender as Button);
    PopUpButton.ContextMenu.IsEnabled = true;
    PopUpButton.ContextMenu.PlacementTarget = PopUpButton;
    PopUpButton.ContextMenu.Placement = System.Windows.Controls.Primitives.PlacementMode.Center;
    PopUpButton.ContextMenu.VerticalOffset = ((PopUpButton.ContextMenu.Height / 2) + 25);
    PopUpButton.ContextMenu.IsOpen = true;
}
4

1 回答 1

0

如果您想水平居中并将 放在ContextMenu下方,Button则必须将其绑定VerticalOffset到并使用将计算所需垂直偏移的ContextMenua 。您可以传递' 高度以使其更通用。ActualHeightConverterButtonConverterParameter

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        Button PopUpButton = (sender as Button);
        PopUpButton.ContextMenu.IsEnabled = true;
        PopUpButton.ContextMenu.PlacementTarget = PopUpButton;
        PopUpButton.ContextMenu.Placement = System.Windows.Controls.Primitives.PlacementMode.Center;

        Binding b = new Binding("ActualHeight")
        { 
            Source = PopUpButton.ContextMenu, 
            Converter = new HeightToOffsetConverter(), 
            ConverterParameter = PopUpButton.ActualHeight,
        };

        PopUpButton.ContextMenu.SetBinding(ContextMenu.VerticalOffsetProperty, b);
        PopUpButton.ContextMenu.IsOpen = true;
    }

    public class HeightToOffsetConverter : IValueConverter
    {
        public object Convert(object value, Type targetType,
            object parameter, CultureInfo culture)
        {
            double popupHeight = (double)value;
            double buttonHeight = (double)parameter;

            return popupHeight / 2 + buttonHeight / 2;
        }

        public object ConvertBack(object value, Type targetType,
            object parameter, CultureInfo culture)
        {
            return Binding.DoNothing;
        }
    }

您还可以(并且在我看来应该)从 XAML 设置此绑定。

于 2013-06-04T17:42:28.503 回答