stringformat .net wpf image exception-handling ivalueconverter

.net - stringformat - Error de ImageSourceConverter para Source=null



textbox string format wpf (3)

@AresAvatar tiene razón al sugerirle que use un ValueConverter, pero esa implementación no ayuda a la situación. Esto hace:

public class NullImageConverter :IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value == null) return DependencyProperty.UnsetValue; return value; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { // According to https://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter.convertback(v=vs.110).aspx#Anchor_1 // (kudos Scott Chamberlain), if you do not support a conversion // back you should return a Binding.DoNothing or a // DependencyProperty.UnsetValue return Binding.DoNothing; // Original code: // throw new NotImplementedException(); } }

La devolución de DependencyProperty.UnsetValue también soluciona los problemas de rendimiento al arrojar (e ignorar) todas esas excepciones. Devolver un new BitmapSource(uri) también eliminaría las excepciones, pero todavía hay un golpe de rendimiento (y no es necesario).

Por supuesto, también necesitará la plomería:

En recursos:

<local:NullImageConverter x:Key="nullImageConverter"/>

Tu imagen:

<Image Source="{Binding Path=ImagePath, Converter={StaticResource nullImageConverter}}"/>

Estoy vinculando la propiedad Fuente de una Imagen a una cadena. Esta cadena puede ser nula, en cuyo caso simplemente no quiero mostrar una imagen. Sin embargo, obtengo lo siguiente en mi salida de depuración:

System.Windows.Data Error: 23: No se puede convertir ''<null>'' del tipo ''<null>'' para escribir ''System.Windows.Media.ImageSource'' para la cultura ''en-AU'' con conversiones predeterminadas; considere usar la propiedad Convertidor de Enlace. NotSupportedException: ''System.NotSupportedException: ImageSourceConverter no puede convertir desde (null). en System.ComponentModel.TypeConverter.GetConvertFromException (Valor del objeto) en System.Windows.Media.ImageSourceConverter.ConvertFrom (ITypeDescriptorContext context, CultureInfo culture, Object value) en MS.Internal.Data.DefaultValueConverter.ConvertHelper (Object o, Type destinationType, DependencyObject targetElement, CultureInfo culture, Boolean isForward) ''

Prefiero que esto no se muestre porque es solo ruido, ¿hay alguna forma de suprimirlo?


Enlaza tu imagen directamente en un objeto y devuelve "UnsetValue" si es necesario

<Image x:Name="Logo" Source="{Binding ImagePath}" />

La propiedad en su ViewModel:

private string _imagePath = string.Empty; public object ImagePath { get { if (string.IsNullOrEmpty(_imagePath)) return DependencyProperty.UnsetValue; return _imagePath; } set { if (!(value is string)) return; _imagePath = value.ToString(); OnPropertyChanged("ImagePath"); } }


Use un convertidor de valor:

En recursos:

>local:IconPathConverter x:Key="iconPathConverter" />

Tu imagen:

<Image Source="{Binding Path=ImagePath, Converter={StaticResource iconPathConverter}}" />

El convertidor:

/// <summary> /// Prevents a null IconPath from being a problem /// </summary> public class IconPathConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value == null || value is string && ((string)value).Length == 0) return (ImageSource)null; return value; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } }