System.Drawing.Point的转换器到"System.Windows.Point" [英] Converter of System.Drawing.Point' to 'System.Windows.Point
问题描述
我试图在WPF中绘制几个实体.我的收藏集中包含System.Drawing.Rectangle对象,当我尝试访问WPF XAML中这些对象的位置时,出现以下错误
I am trying to draw few entities in WPF. My collection contains System.Drawing.Rectangle objects, When I try to access the location of those objects in WPF XAML I am getting following error
无法创建默认转换器以在类型"System.Drawing.Point"和"System.Windows.Point"之间执行单向"转换.考虑使用Binding的Converter属性
Cannot create default converter to perform 'one-way' conversions between types 'System.Drawing.Point' and 'System.Windows.Point'. Consider using Converter property of Binding
我知道我必须使用一些valueconverter.您能否指导我如何将System.Drawing.Point'转换为'System.Windows.Point?
I know I have to use some valueconverter. Could you please guide me how to convert System.Drawing.Point' to'System.Windows.Point?
更新:
以下代码给出了一些例外情况
Following code gives some exception
public class PointConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
System.Windows.Point pt = (Point)(value);
return pt;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
XAML:
<PathFigure StartPoint= "{Binding BoundingRect.Location, Converter={StaticResource PointConverter}}">
推荐答案
我想您会得到InvalidCastException
,除非它们之间存在隐式或显式转换,否则不能将一种类型转换为另一种类型.请记住,演员不同,转换不同.以下代码将System.Drawing.Point
转换为System.Windows.Point
,反之亦然.
I guess you'd have got InvalidCastException
, you can't just cast one type to another unless implicit or explicit conversion exist between them. Remember cast is different and convert is different. Following code converts System.Drawing.Point
to System.Windows.Point
and viceversa.
public class PointConverter : System.Windows.Data.IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
System.Drawing.Point dp = (System.Drawing.Point)value;
return new System.Windows.Point(dp.X, dp.Y);
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
System.Windows.Point wp = (System.Windows.Point) value;
return new System.Drawing.Point((int) wp.X, (int) wp.Y);
}
}
如果System.Drawing.Point
来自Windows窗体的鼠标事件,例如单击事件,则System.Drawing.Point
不能以这种方式直接转换为System.Windows.Point
,因为每个坐标系可能不同.有关更多信息,请参见 https://stackoverflow.com/a/19790851/815724 .
If the System.Drawing.Point
comes from a Windows Forms mouse event, such as a click event, a System.Drawing.Point
can't be directly converted to System.Windows.Point
in this way, since the coordinate systems of each may differ. See https://stackoverflow.com/a/19790851/815724 for more information.
这篇关于System.Drawing.Point的转换器到"System.Windows.Point"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!