C# 集合DP的WPF TypeConversionAttribute
我有一个ObservableCollection作为自定义控件中的依赖属性(比如Points) 我想像这样初始化它C# 集合DP的WPF TypeConversionAttribute,c#,wpf,wpf-controls,C#,Wpf,Wpf Controls,我有一个ObservableCollection作为自定义控件中的依赖属性(比如Points) 我想像这样初始化它 <MyControl Points="1,1, 2,2"/> 如何定义和创建特定DP的typeconverter 我知道有一个专门的points collection类带有内置的typeconverter,但我不能使用它。好问题。有一种方法可以做到这一点——将点的DP更改为对象/字符串类型(以避免无效的强制转换异常),并在DP更改事件处理程序中进行转换。最终,您不
<MyControl Points="1,1, 2,2"/>
如何定义和创建特定DP的typeconverter
我知道有一个专门的points collection类带有内置的typeconverter,但我不能使用它。好问题。有一种方法可以做到这一点——将点的DP更改为对象/字符串类型(以避免无效的强制转换异常),并在DP更改事件处理程序中进行转换。最终,您不会有什么损失—DP系统并不完全是一个类型安全的框架 那就行了。我完全可以将JSON视为序列化数据的格式
另一种方法是在可观察的集合之上引入更高级别的抽象。通常这会减轻对XAML的压力。您可以在CLR属性包装器上为依赖项属性指定一个
类型转换器。像这样:
public class MyControl : Control
{
[TypeConverter(typeof(MyStringToPointCollectionConverter))]
public ObservableCollection<Point> Points {
get { return (ObservableCollection<Point>)GetValue(Points yProperty); }
set { SetValue(Points Property, value); }
}
...
}
公共类MyControl:Control
{
[TypeConverter(typeof(MyStringToPointCollectionConverter))]
公众可观测收集点{
获取{return(observateCollection)GetValue(Points yProperty);}
set{SetValue(Points属性,value);}
}
...
}
转换器看起来像这样:
public class MyStringToPointCollectionConverter : TypeConverter {
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) {
if (sourceType == typeof(string)) {
return true;
}
return false;
}
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) {
var stringValue = value as string;
if (stringValue != null) {
var result = new ObservableCollection<Point>();
// Here goes the logic of converting the given string to the list of points
return result;
}
return null;
}
}
公共类MyStringToPointCollectionConverter:TypeConverter{
公共覆盖布尔CanConvertFrom(ITypeScriptorContext上下文,类型sourceType){
if(sourceType==typeof(string)){
返回true;
}
返回false;
}
公共重写对象ConvertFrom(ITypeDescriptorContext上下文,System.Globalization.CultureInfo区域性,对象值){
var stringValue=作为字符串的值;
if(stringValue!=null){
var结果=新的ObservableCollection();
//下面是将给定字符串转换为点列表的逻辑
返回结果;
}
返回null;
}
}
[TypeConverter(typeof(*)是一款非常流畅的产品。谢谢你,效果很好。但它似乎对VS设计师不起作用。有什么想法吗?@NVM-没有,对不起。不知道VS designer是如何工作的。但您可能希望使用反射器来查看如何实现这一点,例如,对于Path对象的数据属性。