【发布时间】:2018-06-04 10:59:41
【问题描述】:
我有一个使用转换器的 WPF 应用程序:
public class MyResultImageConverter : IValueConverter
{
public Image OkImage { get; set; }
public Image FailImage { get; set; }
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null || !(value is MyCustomObject))
{
return null;
}
Image img = null;
MyCustomObjectdbr = (MyCustomObject)value;
switch (MyCustomObjectdbr.Code)
{
case (int)MyEnum.OK:
img = this.OkImage;
break;
case (int)MyEnum.NOK:
img = this.FailImage;
break;
default:
break;
}
return img;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
然后在窗口资源中我做:
<myConverters:MyResultImageConverter
OkImage="/My.Tools.Graphics;component/Images/Accept.png"
FailImage="/My.Tools.Graphics;component/Images/Cancel.png"
x:Key="MyResultImageConverter"/>
此转换器稍后在 DataGridTemplateColumn 中使用:
<dg:DataGridTemplateColumn
Width="SizeToCells"
IsReadOnly="True">
<dg:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Image Source="{Binding Path=MyResult, Converter={StaticResource MyResultImageConverter}}" />
</DataTemplate>
</dg:DataGridTemplateColumn.CellTemplate>
</dg:DataGridTemplateColumn>
编译器在尝试为转换器设置 Image 属性时抛出错误:
<myConverters:MyResultImageConverter
OkImage="/My.Tools.Graphics;component/Images/Accept.png"
FailImage="/My.Tools.Graphics;component/Images/Cancel.png"
x:Key="MyResultImageConverter"/>
或多或少,翻译它说:
无法赋值“/My.Tools.Graphics;component/Images/Accept.png” 到 OkImage 的属性。 'Image' 类型的 'OkImage' 属性不能 指定为字符串。
My.Tools.Graphics 是添加到我的 Visual Studio 解决方案中的 DLL,其中包含一个名为 Images 的文件夹,其中包含 png 图像。
【问题讨论】:
标签: c# wpf .net-3.5 ivalueconverter