Don't crash if Imaging.CreateBitmapSourceFromHIcon fails

This commit is contained in:
Antony Male 2016-01-30 14:19:26 +00:00
parent de14009358
commit 78e7da40b4
2 changed files with 18 additions and 6 deletions

View File

@ -5,6 +5,7 @@ using System.Windows;
using System.Windows.Data;
using System.Windows.Interop;
using System.Windows.Media.Imaging;
using Stylet.Logging;
namespace Stylet.Xaml
{
@ -14,6 +15,8 @@ namespace Stylet.Xaml
[SuppressMessage("StyleCop.CSharp.ReadabilityRules", "SA1126:PrefixCallsCorrectly", Justification = "Don't agree with prefixing static method calls with the class name")]
public class IconToBitmapSourceConverter : IValueConverter
{
private static readonly ILogger logger = LogManager.GetLogger(typeof(IconToBitmapSourceConverter));
/// <summary>
/// Singleton instance of this converter. Usage e.g. Converter="{x:Static s:IconToBitmapSourceConverter.Instance}"
/// </summary>
@ -32,13 +35,22 @@ namespace Stylet.Xaml
var icon = value as Icon;
if (icon == null)
return null;
var bs = Imaging.CreateBitmapSourceFromHIcon(icon.Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
bs.Freeze();
return bs;
try
{
var bs = Imaging.CreateBitmapSourceFromHIcon(icon.Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
bs.Freeze();
return bs;
}
catch (Exception e)
{
logger.Error(e, String.Format("Error trying to call CreateBitmapSourceFromHIcon: {0}", e.Message));
return null;
}
}
/// <summary>
/// Converts a value back. Not implemented.
/// Converts a value back. Not supported.
/// </summary>
/// <param name="value">value, as produced by target</param>
/// <param name="targetType">target type</param>
@ -47,7 +59,7 @@ namespace Stylet.Xaml
/// <returns>Converted back value</returns>
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
throw new NotSupportedException();
}
}
}

View File

@ -39,7 +39,7 @@ namespace StyletUnitTests
[Test]
public void ConvertBackThrows()
{
Assert.Throws<NotImplementedException>(() => this.converter.ConvertBack(null, null, null, null));
Assert.Throws<NotSupportedException>(() => this.converter.ConvertBack(null, null, null, null));
}
}
}