我假设有一种方法可以告诉WPF如何将字符串目标转换为源类型而无需指定IValueConverter。例如,WPF会将字符串转换为颜色。我想如果我的类型支持从字符串到我的类型的显式转换,这就足够了。但是这不起作用。有没有办法?如何告诉WPF无需IValueConverter将目标转换为我的源类型
0
A
回答
1
是的,但是你必须为你的类型定义一个类型转换器。只需重写ToString(),就可以从类型转换为字符串。要走另一个方向,你需要一个类型转换器。例如...
public class PartNumberConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(string);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
if(value is string)
{
return new PartNumber(value as string);
}
return null;
}
}
[TypeConverter(typeof(PartNumberConverter))]
public class PartNumber
{
public PartNumber(string s)
{
string[] e = s.Split('-');
if(e.Length==3)
{
_a = Convert.ToInt32(e[0]);
_b = Convert.ToInt32(e[1]);
_c = Convert.ToInt32(e[2]);
}
}
public PartNumber(int a, int b, int c)
{
_a = a;
_b = b;
_c = c;
}
int _a = 0;
int _b = 0;
int _c = 0;
public override string ToString()
{
return _a + "-" + _b + "-" + _c;
}
}
所以不是的IValueConverter但仍然是一个转换器:)
+0
注意:为了OP的缘故。 'IValueConverter'是一个运行时工具。这里列出的'TypeConverter'是一个设计时间工具。如果你直接绑定到你的对象,那么'IValueConverter'可能是正确的工具。如果你在XAML中创建你的类型的实例,那么'TypeConverter'是正确的工具。 –
+0
谢谢你的回答。我想让我的类型被XAML程序员使用,而不必创建IValueConverter。这工作完美。谢谢。 – user3905162
相关问题
- 1. 无法将源类型转换为目标类型
- 2. UIImage.AsJPEG()返回“无法从源类型转换为目标类型”。
- 3. 无法转换源类型system.nullable目标类型为int
- 4. Unity C#InvalidCastException:无法从源类型转换为目标类型
- 5. 无法从源类型转换为目标类型Json
- 6. 无法从源类型转换为目标类型迭代转换
- 7. 无法将源类型转换为目标类型List <KeyValuePair> Linq
- 8. 无法将源类型'字符串'转换为目标类型'uint'错误c#
- 9. 无法将源接口类型转换为目标接口类型
- 10. 如何将源类型'System.Nullable <bool>'转换为目标类型'bool'
- 11. 不能从源类型转换为目标类型
- 12. Monotouch绑定 - “不能从源类型转换为目标类型。”
- 13. 请告诉我如何将XML文件转换为数据表
- 14. 有人能告诉我如何将ActionScript 2转换为actionscript3吗?
- 15. 编译器告诉我“不能将类型'char'隐式转换为'bool'
- 16. 如何将强类型的DataTable转换为无类型的DataTable
- 17. 无法将源类型“System.Web.UI.Control”为目标类型“System.Web.UI.WebControls.TextBox”
- 18. 将webapp资源转换为目标
- 19. 如何告诉AutoMapper在我的目标类型上使用方法?
- 20. Javascript,类型转换需要(我认为)
- 21. 无法将System.String转换为类类型
- 22. 无法将源类型“无效”为目标类型“的ICollection <Character>”
- 23. WPF IValueConverter - 将多个值转换为单个值
- 24. 无法java.lang.String类型的值转换为所需的类型java.util.Date
- 25. 创建通用的IValueConverter数据类型转换为字符串
- 26. 如何将System.Windows.Controls类型转换为System.Windows.Forms wpf
- 27. 无法将源类型'System Linq IQueryable <decimal>'转换为目标类型十进制
- 28. Neo4j:spring-data-neo4j,如何将结果转换为我的类型类?
- 29. 我需要将这两个函数从javascript更改为jQuery任何一个可以告诉我如何转换
- 30. [InvalidCastException的:无法转换类型 'System.DBNull' 的目的为类型 'System.String']
你可以注册一个[类型转换器(https://msdn.microsoft.com/en-us/library/system .componentmodel.typeconverter(v = vs.110)的.aspx)。 – Clemens