【问题标题】:WPF MVVM Binding Window Icon to a property in view modelWPF MVVM将窗口图标绑定到视图模型中的属性
【发布时间】:2017-12-18 10:52:13
【问题描述】:

我有一个 WPF MVVM 应用程序。在我的项目属性中,我在“应用程序”选项卡中设置了图标。

我正在尝试统一从整个应用程序的不同位置获取窗口图标的方式。所以我在一个类中创建了一个扩展方法:

internal static class IconUtilities
{
    [DllImport("gdi32.dll", SetLastError = true)]
    private static extern bool DeleteObject(IntPtr hObject);

    public static ImageSource ToImageSource(this Icon icon)
    {
        Bitmap bitmap = icon.ToBitmap();
        IntPtr hBitmap = bitmap.GetHbitmap();

        ImageSource wpfBitmap = Imaging.CreateBitmapSourceFromHBitmap(
            hBitmap,
            IntPtr.Zero,
            Int32Rect.Empty,
            BitmapSizeOptions.FromEmptyOptions());

        if (!DeleteObject(hBitmap))
        {
            throw new Win32Exception();
        }

        return wpfBitmap;
    }
}

在我的视图模型中还有一个公共属性:

public Icon WindowIcon
{
    get
    {
        return Icon.ExtractAssociatedIcon(Assembly.GetExecutingAssembly().Location);
    }
}

public ImageSource GetWindowIcon()
{
    return WindowIcon.ToImageSource();
}

因此,无论何时我需要在我的视图模型中获取应用程序图标,我都会调用此属性来获取它。所以我确保我始终使用相同的应用程序图标。

现在,我正在尝试通过执行以下操作将此属性绑定到窗口图标:

<Window x:Name="MainWindow" x:Class="My.Apps.WPF.wMain"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:my="http://schemas.microsoft.com/wpf/2008/toolkit" 
    Icon="{Binding WindowIcon}"
/>
</Window>

但在运行时显示的窗口图标是默认的,而不是在项目属性中设置的。我做错了什么?

尝试#1:

这是在 InitializeComponents 之前调用的,所以我已经进入 Window Loaded 事件。

现在,从窗口:

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    this.Icon = ((wMainViewModel)this.DataContext).WindowIcon;
}

我得到错误:

Cannot convert implicitly 'System.Drawing.Icon' type into 'System.Windows.Media.ImageSource'

所以我尝试在下面做:

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    this.Icon = ((wMainViewModel)this.DataContext).GetWindowIcon();
}

现在我得到了错误:

ImageSource for Icon property should be an icon file.

测试应用:


简单的 WPF 测试应用程序(不是 MVVM) - 仅用于测试目的

下面我编写了一个完整的 WPF 应用程序(不是 MVVM),取自 here 并添加了一些代码。此示例代码与上面发布的所有代码不同:目的 此示例的目的是显示将 ImageSource 分配给 窗口图标。它已经在带有 NET Framework 3.5 和 Visual Studio 2015 和 NET Framework 3.5 的 Visual Studio 2008 中进行了测试。这两种情况在设置 this.Icon 时在 SplashScreen 代码隐藏构造函数中都失败,请参阅下面的代码。

另外,用于测试的图标文件 (*.ico) 是:“C:\Program Files\Internet Explorer\images\bing.ico”。此图标文件已添加到我的项目中,并且我已将构建操作设置为资源,而不是将其复制到输出目录作为其属性。

另外,在项目属性的应用程序选项卡中,我选择了这个图标 (bing.ico) 作为应用程序的图标。此图标将使用以下行从代码中提取:

System.Drawing.Icon.ExtractAssociatedIcon(Assembly.GetExecutingAssembly().Location);

稍后在我的代码中查看,就在 SplashScreen 代码隐藏中,在构造函数中。

补充说明:我有 Windows 8.1 Pro x64。

App.cs:

using System;
using System.Drawing;
using System.Reflection;
using System.Threading;
using System.Windows;

namespace SplashDemo
{
    class App: Application
    {
        [STAThread ( )]
        static void Main ( )
        { 
            Icon ico = Icon.ExtractAssociatedIcon(Assembly.GetExecutingAssembly().Location);
            Splasher.Splash = new SplashScreen(ico);
            Splasher.ShowSplash();

            for ( int i = 0; i < 5000; i++ )
            {                
                DispatcherHelper.DoEvents();
                Thread.Sleep ( 1 );
            }

            new App ( );
        }

        public App ( )
        {         
            StartupUri = new System.Uri ( "MainWindow.xaml", UriKind.Relative );

            Run ( );            
        }
    }
}

注意事项:图标对象的类型为 System.Drawing.Icon

DispatcherHelper 类:

using System;
using System.Security.Permissions;
using System.Windows.Threading;

namespace SplashDemo
{
    public static class DispatcherHelper
    {
        /// <summary>
        /// Simulate Application.DoEvents function of <see cref=" System.Windows.Forms.Application"/> class.
        /// </summary>
        [SecurityPermissionAttribute ( SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode )]
        public static void DoEvents ( )
        {
            DispatcherFrame frame = new DispatcherFrame ( );
            Dispatcher.CurrentDispatcher.BeginInvoke ( DispatcherPriority.Background,
                new DispatcherOperationCallback ( ExitFrames ), frame );

            try
            {
                Dispatcher.PushFrame ( frame );
            }
            catch ( InvalidOperationException )
            {
            }
        }

        private static object ExitFrames ( object frame )
        {
            ( ( DispatcherFrame ) frame ).Continue = false;

            return null;
        }
    }
}

Splasher 类:

using System;
using System.Windows;

namespace SplashDemo
{
    /// <summary>
    /// Helper to show or close given splash window
    /// </summary>
    public static class Splasher
    {
        /// <summary>
        /// 
        /// </summary>
        private static Window mSplash;

        /// <summary>
        /// Get or set the splash screen window
        /// </summary>
        public static Window Splash
        {
            get
            {
                return mSplash;
            }
            set
            {
                mSplash = value;
            }
        }

        /// <summary>
        /// Show splash screen
        /// </summary>
        public static void ShowSplash ( )
        {
            if ( mSplash != null )
            {
                mSplash.Show ( );
            }
        }
        /// <summary>
        /// Close splash screen
        /// </summary>
        public static void CloseSplash ( )
        {
            if ( mSplash != null )
            {
                mSplash.Close ( );

                if ( mSplash is IDisposable )
                    ( mSplash as IDisposable ).Dispose ( );
            }
        }
    }
}

SplashScreen 类(代码隐藏):

using System.Drawing;
using System.Reflection;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace SplashDemo
{
    /// <summary>
    /// Interaction logic for SplashScreen.xaml
    /// </summary>
    public partial class SplashScreen : Window
    {
        public SplashScreen ()
        {
            InitializeComponent();
        }

        public SplashScreen(Icon icon) : this()
        { 
            // BELOW LINE CRASHES
            this.Icon =  System.Drawing.Icon.ExtractAssociatedIcon(Assembly.GetExecutingAssembly().Location);
        }
    }
}

SplashScreen 类的注意事项:

  • 如果我使用 this.Icon = System.Drawing.Icon.ExtractAssociatedIcon(Assembly.GetExecutingAssembly().Location);它在编译时抛出以下错误:

无法将类型“system.drawing.icon”隐式转换为 'system.windows.media.imagesource'

  • 如果我将此行替换为:this.Icon = icon.ToImageSource2();

然后它抛出一个运行时错误(不是编译错误),一个 System.InvalidOperationException:

Icon 属性的ImageSource 必须是图标文件

闪屏视图:

<Window 
    x:Class="SplashDemo.SplashScreen"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:SplashDemo" 

    Title="SplashScreen" Height="236" Width="414" WindowStartupLocation="CenterScreen" WindowStyle="None" 
    Background="Orange" BorderBrush="DarkOrange" BorderThickness="3" 
    ShowInTaskbar="False" ResizeMode="NoResize">

    <Grid>
        <Grid.RowDefinitions>            
            <RowDefinition Height="2*" />
            <RowDefinition Height="0.5*" />
        </Grid.RowDefinitions>

        <Label Grid.Row="0" Name="label1" FontSize="48" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Foreground="MintCream">
            <Label.BitmapEffect>
                <OuterGlowBitmapEffect GlowSize="15" />
            </Label.BitmapEffect> Splash screen
        </Label>

        <Label Grid.Row="1" x:Name="CurrentTask" 
               FontFamily="Microsoft Sans Serif" FontSize="18" FontStyle="Italic"  
               Foreground="White" Content="Loading">
            <Label.Style>
                <Style TargetType="Label">
                    <Style.Triggers>
                        <EventTrigger RoutedEvent="Label.Loaded">
                            <EventTrigger.Actions>
                                <BeginStoryboard>
                                    <Storyboard>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Content" Duration="00:00:00.8" RepeatBehavior="Forever">
                                            <DiscreteObjectKeyFrame KeyTime="00:00:00.0" Value="Loading"/>
                                            <DiscreteObjectKeyFrame KeyTime="00:00:00.2" Value="Loading."/>
                                            <DiscreteObjectKeyFrame KeyTime="00:00:00.4" Value="Loading.."/>
                                            <DiscreteObjectKeyFrame KeyTime="00:00:00.6" Value="Loading..."/>
                                        </ObjectAnimationUsingKeyFrames>
                                    </Storyboard>
                                </BeginStoryboard>
                            </EventTrigger.Actions>
                        </EventTrigger>
                    </Style.Triggers>
                </Style>
            </Label.Style>
        </Label>

    </Grid>
</Window>

主窗口视图:

<Window 
    x:Class="SplashDemo.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Main window" Height="332" Width="539" WindowStartupLocation="CenterScreen">
    <Grid>
        <Label Margin="39,59,21,102" Name="label1" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" FontSize="36">Application window</Label>
    </Grid>
</Window>

主窗口代码隐藏:

using System.Windows;

namespace SplashDemo
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow ( )
        {
            InitializeComponent ( );
        }
    }
}

IconUtilities 类(从 System.Drawing.Icon 转换为 System.Windows.Media.ImageSource):

using System;
using System.ComponentModel;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace SplashDemo
{
    internal static class IconUtilities
    {
        [DllImport("gdi32.dll", SetLastError = true)]
        private static extern bool DeleteObject(IntPtr hObject);

        public static ImageSource ToImageSource(this Icon icon)
        {
            Bitmap bitmap = icon.ToBitmap();
            IntPtr hBitmap = bitmap.GetHbitmap();

            ImageSource wpfBitmap = Imaging.CreateBitmapSourceFromHBitmap(
                hBitmap,
                IntPtr.Zero,
                Int32Rect.Empty,
                BitmapSizeOptions.FromEmptyOptions());

            if (!DeleteObject(hBitmap))
            {
                throw new Win32Exception();
            }

            return wpfBitmap;
        }

        // Below a simple method without extra objects:
        public static ImageSource ToImageSource2(this Icon icon)
        {
            ImageSource imageSource = Imaging.CreateBitmapSourceFromHIcon(
                                          icon.Handle,
                                          Int32Rect.Empty,
                                          BitmapSizeOptions.FromEmptyOptions());

            return imageSource;
        }
    }
}

注意事项:

  • ImageSource 的类型为 System.Windows.Media.ImageSource
  • ToImageSource2 的作用与 ToImageSource 相同,但没有额外的对象,请参阅 here。

【问题讨论】:

  • 如果有错误,请引用确切的错误详细信息。
  • @AndyG 我已更正。

标签: c# wpf mvvm window


【解决方案1】:

绑定

<Window ... Icon="{Binding WindowIcon}">

要求WindowIcon 属性是ImageSource

所以您当然希望实现如下所示的视图模型,它在 Loaded 事件处理程序中无需任何代码即可工作。

public ImageSource WindowIcon
{
    get { return GetWindowIcon().ToImageSource(); }
}

public static Icon GetWindowIcon()
{
    return Icon.ExtractAssociatedIcon(Assembly.GetExecutingAssembly().Location);
}

【讨论】:

  • 首先我尝试从 xmal 绑定窗口图标以查看模型属性,但它不起作用,我的图标没有显示,而是显示为默认图标。然后在尝试 #1 中,我没有在 xaml 中将图标绑定到视图模型属性,而是从 Window 加载事件中设置它,然后我得到了这些错误。
  • 我的答案中的代码有效。我已经测试过了。您是否将 Window 的 DataContext 属性分配给您的视图模型类的实例?
  • 是的,我已将窗口的 datacontext 属性分配给视图模型类的实例,但在运行时出现以下错误(或多或少翻译自西班牙语):值 'System.Windows.Data.无法将 BindingExpression 分配给对象“My.Apps.WPF.wMain”的“Icon”属性。 Icon 属性的 ImageSource。它必须是一个图标文件。标记文件中的“System.Windows.Data.Binding”对象出错。
  • 您是否使用了该答案中显示的方法和属性完全,而没有任何 Loaded 事件处理程序?
  • 是的,我正在使用您在答案中发布的 2 种方法,并且我没有使用 Window Loaded 事件。
【解决方案2】:

您不能使用ImageSource 进行绑定,请查看official documentation。您可以看到Window.Icon 属性接受BitmapFrame 作为其输入。

以下是官方文档中提供的代码,描述了如何用代码设置图标。

// Set an icon using code
Uri iconUri = new Uri("pack://application:,,,/WPFIcon2.ico", UriKind.RelativeOrAbsolute);
this.Icon = BitmapFrame.Create(iconUri);

在尝试了所有其他数据类型都没有成功后,我猜它只接受BitmapFrame???在微软的代码中,它使用BitmapFrame.Create(iconUri); 另外,我遇​​到了this question,它表明调试器将窗口图标识别为System.Windows.Media.Imaging.BitmapFrameDecode,但不是ImageSource。 因此,忘记转换为ImageSource 或System.Drawing.Icon,只需使用BitmapFrame。只需将您的 ImageSource 部分更改为以下即可解决问题。

在 MainWindowViewModel.cs 中

private BitmapFrame _bfWindowIcon;

public BitmapFrame BfWindowIcon
{
    get { 
        return _bfWindowIcon;
    }
    set {
        _bfWindowIcon = value;
        OnPropertyChanged(nameof(BfWindowIcon));
    }
}

private void VoidUpdateIcon() {
   IconBitmapDecoder ibd = new IconBitmapDecoder(
   new Uri(@"pack://application:,,,/Resources/Icon_Green.ico", UriKind.RelativeOrAbsolute),
   BitmapCreateOptions.None,
   BitmapCacheOption.Default);
   BfWindowIcon = ibd.Frames[0];
}

在 MainWindow.xaml 中

<Window x:Class=
...
...
Icon="{Binding BfWindowIcon}">
    <Window.DataContext>
        <viewmodels:MainWindowViewModel />
    </Window.DataContext>
...
...
</Window>

在使用IValueConverter 时绑定Window.Icon 需要一些技巧,因为.xaml 中的StaticResource 在后面。下面是我如何使用 IValueConverter

转换器.cs

public class ServiceStateToWindowIconConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            ServiceState val = (ServiceState)value;
            if (val == ServiceState.OK)
            { 
                return BfGetBitmapFrameByURI("pack://application:,,,/ProjectName;component/Resources/Icon_Green.ico");
            }
            else if (val == ServiceState.Warning)
            {
                return BfGetBitmapFrameByURI("pack://application:,,,/ProjectName;component/Resources/Icon_Orange.ico");
            }
            else
            {
                return BfGetBitmapFrameByURI ("pack://application:,,,/ProjectName;component/Resources/Icon_Red.ico");
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        private BitmapFrame BfGetBitmapFrameByURI(string strUri)
        {
            IconBitmapDecoder ibd = new IconBitmapDecoder(
            new Uri(strUri, UriKind.RelativeOrAbsolute),
            BitmapCreateOptions.None,
            BitmapCacheOption.Default);
            return ibd.Frames[0];
        }

MainWindow.xaml

<Window 
xmlns:Converters="clr-namespace:YourNameSpace"
...
... 
Background="Transparent">
...
    <Window.Resources>
        <Converters:ServiceStateToWindowIconConverter x:Key="ServiceStateToWindowIconConverter"/>
    </Window.Resources>
    <Window.Icon>
        <Binding Path="ServiceStateForConverter" Converter="{StaticResource ServiceStateToWindowIconConverter}"/>
    </Window.Icon>
...
</Window>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-25
    • 1970-01-01
    相关资源
    最近更新 更多