似乎当ContextMenu
已加载ScrollContentPresenter
由于菜单大小不正确,请剪裁ItemPresenter
of the MenuItem
(下面是显示该问题的可视化树的删节版本)。
PopupRoot, Acutal Width: 219,027, Desired Width: 219,027
Decorator, Acutal Width: 219,027, Desired Width: 219,027
NonLogicalAdornerDecorator, Acutal Width: 219,027, Desired Width: 219,027
ContextMenuProxy, Acutal Width: 219,027, Desired Width: 219,027
SystemDropShadowChrome, Acutal Width: 214,027, Desired Width: 219,027
Border, Acutal Width: 214,027, Desired Width: 214,027
Grid, Acutal Width: 212,027, Desired Width: 212,027
Rectangle, Acutal Width: 28,000, Desired Width: 32,000
Rectangle, Acutal Width: 1,000, Desired Width: 31,000
Rectangle, Acutal Width: 1,000, Desired Width: 32,000
ScrollViewer, Acutal Width: 210,027, Desired Width: 212,027
Grid, Acutal Width: 210,027, Desired Width: 210,027
Border, Acutal Width: 210,027, Desired Width: 210,027
ScrollContentPresenter, Acutal Width: 210,027, Desired Width: 210,027
ItemsPresenter, Acutal Width: 241,047, Desired Width: 245,047
使 的测量无效ContextMenu
的视觉根(PopupRoot
)加载菜单时应导致布局更新以显示正确的边界ItemsPresenter
.
菜单的 Load 事件的处理程序:
private void mainMenu_Loaded(object sender, RoutedEventArgs e)
{
if (sender != null)
{
ContextMenu menu = sender as ContextMenu;
if (menu != null)
{
// get the visual root for the context menu
var root = (FrameworkElement)GetVisualTreeRoot(menu);
// invalidate the menu's layout
root.InvalidateMeasure();
}
}
}
获取VisualTreeRoot方法:
private DependencyObject GetVisualTreeRoot(DependencyObject control)
{
DependencyObject parent = VisualTreeHelper.GetParent(control);
if (parent != null)
{
return GetVisualTreeRoot(parent);
}
else
{
return control;
}
}