【发布时间】: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 我已更正。