0
我已綁定我的菜單項,使用下面的代碼菜單項的模型類: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();
}
}
的問題是,而不是一個圖標,我得到了我的菜單中的字符串。