【发布时间】:2016-05-21 05:03:56
【问题描述】:
我的视图中有这个变量绑定:
<Image Source="{Binding Path=GrappleTypeVar, Source={StaticResource CustomerData}, Converter={StaticResource GrappleDataConverter}}" Width="40" Height="40"/>
然后,这个转换器:
public class GrappleDataConverter : IValueConverter
{
public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value != null)
{
int currentType = (int)value;
if (Enum.IsDefined(typeof(GrappleType), currentType))
{
switch ((GrappleType)currentType)
{
case GrappleType.Hydraulic:
return String.Empty;
case GrappleType.Parallel:
return "/GUI;component/Images/040/SensorSoft.png";
}
}
}
// Not defined... Set unknown image
return String.Empty;
}
public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new System.NotImplementedException();
}
}
使用该代码,我的结果窗口返回了很多类型的绑定错误:
System.Windows.Data 信息:10:无法使用绑定检索值,并且不存在有效的备用值;改用默认值。绑定表达式:路径=GrappleTypeVar; DataItem='CustomerData' (HashCode=50504364);目标元素是'图像'(名称='');目标属性是“源”(类型“ImageSource”) System.Windows.Data 错误:23:无法使用默认转换将 '' 从类型 'String' 转换为类型 'System.Windows.Media.ImageSource' 用于 'en-US' 文化;考虑使用 Binding 的 Converter 属性。 NotSupportedException:'System.NotSupportedException: ImageSourceConverter 无法从 System.String 转换。
查看该错误,我找到了解决方案: ImageSourceConverter error for Source=null
而且我更改了我的代码:
case GrappleType.Hydraulic:
return String.Empty;
为
case GrappleType.Hydraulic:
return DependencyProperty.UnsetValue;
现在应用程序运行更流畅了,但在结果窗口中出现以下绑定错误: System.Windows.Data 信息:10:无法使用绑定检索值,并且不存在有效的备用值;改用默认值。绑定表达式:路径=GrappleTypeVar; DataItem='CustomerData' (HashCode=62171008);目标元素是'图像'(名称='');目标属性是'Source'(类型'ImageSource')
谁能帮帮我?有没有可能解决这个错误?
谢谢!
【问题讨论】:
-
Image.Source是一个抽象类型ImageSource(不能被实例化)。在您的转换器中,您应该返回一个派生类对象,而不是一个字符串,例如BitmapImage。
标签: wpf ivalueconverter