WPF:绑定图标属性到System.Drawing.Icon
问题描述:
我已绑定我的菜单项,使用下面的代码菜单项的模型类:WPF:绑定图标属性到System.Drawing.Icon
<Window.Resources>
<classes:IconConverter x:Key="IconConverter"/>
<Style TargetType="MenuItem" x:Key="BoundMenuItemStyle">
<Setter Property="Header" Value="{Binding Path=Header}" />
<Setter Property="ItemsSource" Value="{Binding Path=Children}" />
<Setter Property="Command" Value="{Binding Path=Command}" />
<Setter Property="Icon" Value="{Binding Path=Icon, Converter={StaticResource IconConverter}}"/>
</Style>
</Window.Resources>
<DockPanel>
<Menu DockPanel.Dock="Top" ItemsSource="{Binding MenuItems}" ItemContainerStyle="{StaticResource BoundMenuItemStyle}"/>
</DockPanel>
模型类的Icon
属性是System.Drawing.Icon
类型。所以我写了一个转换器将其转换为一个ImageSource
:
class IconConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is System.Drawing.Icon)
{
var icon = value as System.Drawing.Icon;
ImageSource imageSource = Imaging.CreateBitmapSourceFromHIcon(
icon.Handle,
System.Windows.Int32Rect.Empty,
System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
return imageSource;
}
return Binding.DoNothing;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
}
的问题是,而不是一个图标,我得到了我的菜单中的字符串。
答
我的问题是,我应该从我的转换器返回Image
控制的实例:
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is System.Drawing.Icon)
{
var icon = value as System.Drawing.Icon;
ImageSource imageSource = Imaging.CreateBitmapSourceFromHIcon(
icon.Handle,
System.Windows.Int32Rect.Empty,
System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
System.Windows.Controls.Image img = new System.Windows.Controls.Image();
img.Source = imageSource;
return img;
}
return Binding.DoNothing;
}