WPF:将Icon属性绑定到System.Drawing.Icon

时间:2015-08-08 05:06:36

标签: c# wpf data-binding

我使用以下代码将菜单项绑定到菜单项模型类:

<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();
    }
}

问题是代替图标,我的菜单中有一个字符串。

1 个答案:

答案 0 :(得分:0)

我的问题是我应该从我的转换器返回var website = ["http://url.com", "http://ebay.com"] var array = []; for (var i=0;i <website.lenght;i++){ $.get(website[i], function(sourcecode) { array.push(sourcecode); }); } console.log(sourcecode); 控件的实例:

Image