![](/img/trans.png)
[英]XamlParseException on System.Drawing.Icon in WPF C#
[英]WPF: bind Icon property to a 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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.