gpt4 book ai didi

wpf - 如何使用 ItemContainerStyle 设置 MenuItem 的图标

转载 作者:行者123 更新时间:2023-12-04 16:41:46 26 4
gpt4 key购买 nike

我正在按照此处绑定(bind) MenuItem 的示例进行操作。到数据对象。

<Menu Grid.Row="0" KeyboardNavigation.TabNavigation="Cycle"
ItemsSource="{Binding Path=MenuCommands}">
<Menu.ItemContainerStyle>
<Style>
<Setter Property="MenuItem.Header" Value="{Binding Path=DisplayName}"/>
<Setter Property="MenuItem.ItemsSource" Value="{Binding Path=Commands}"/>
<Setter Property="MenuItem.Command" Value="{Binding Path=Command}"/>
<Setter Property="MenuItem.Icon" Value="{Binding Path=Icon}"/>
</Style>
</Menu.ItemContainerStyle>
</Menu>

除了 MenuItem 之外,一切都很顺利。的图标显示为字符串 System.Drawing.Bitmap .有问题的位图由编译资源中的数据对象返回。
internal static System.Drawing.Bitmap folder_page
{
get
{
object obj = ResourceManager.GetObject("folder_page", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}

我究竟做错了什么?

最佳答案

肯特(当然)有正确的答案。 但我想我会继续发布从 System.Drawing.Bitmap (Windows Forms) 转换为 System.Windows.Windows.Media.BitmapSource (WPF) 的转换器的代码。 ...因为这是一个常见的问题/问题。

这需要三个步骤:

  • 在装订中使用图像转换器。
  • 创建转换器。
  • 在您的资源中声明转换器。

  • 以下是在绑定(bind)中使用图像转换器的方法 :
    <Setter
    Property="MenuItem.Icon"
    Value="{Binding Path=Icon, Converter={StaticResource imageConverter}}"
    />

    而且,这里是转换器的代码 (将其放入名为 ImageConverter.cs 的文件中)并将其添加到您的项目中:
    [ValueConversion(typeof(Image), typeof(string))]
    public class ImageConverter : IValueConverter
    {
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
    BitmapSource bitmapSource;

    IntPtr bitmap = ((Bitmap)value).GetHbitmap();
    try
    {
    bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(bitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
    }
    finally
    {
    DeleteObject(bitmap);
    }

    return bitmapSource;
    }

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

    [DllImport("gdi32.dll", CharSet=CharSet.Auto, SetLastError=true)]
    static extern int DeleteObject(IntPtr o);
    }

    这是您在资源部分中声明它的方式 (注意您必须添加的本地命名空间):
    <Window
    x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication2"
    >
    <Window.Resources>
    <local:ImageConverter x:Key="imageConverter"/>
    </Window.Resources>
    <!-- some xaml snipped for clarity -->
    </Window>

    就是这样!

    更新

    在快速搜索类似问题后,我注意到 Lars Truijens指出 here以前的转换器实现泄漏。我已经更新了上面的转换器代码......这样它就不会泄漏。

    有关泄漏原因的更多信息,请参阅此 MSDN link 上的备注部分.

    关于wpf - 如何使用 ItemContainerStyle 设置 MenuItem 的图标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1789778/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com