不显示以编程方式添加的菜单项图标

Menu item icon added programmatically is not displayed

我在尝试以编程方式添加选中图像时遇到显示菜单项图标问题:

private void ObjectsCanvas_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
    ContextMenu cm = new ContextMenu();

    MenuItem mDiag = new MenuItem();
    mDiag.Icon = new System.Windows.Controls.Image
    {
        Source = (new BitmapImage(new Uri("assets/checked-32-context.png", UriKind.Relative)))
    };
    mDiag.Header = Application.Current.Resources["DiagScreenMenuText"].ToString();

    cm.Items.Add(mDiag);
    cm.PlacementTarget = sender as Button;
    cm.IsOpen = true;
}

checked-32-context.png图片只用在这里,不显示:

相对于XAML,需要在后面的代码中指定完整的Resource File Pack URI

mDiag.Icon = new System.Windows.Controls.Image
{
    Source = new BitmapImage(new Uri(
        "pack://application:,,,/assets/checked-32-context.png"))
};

另请注意,这不是相对 URI。