System.Drawing.Point' 到 'System.Windows.Point 的转换器

Rob*_*ech 3 c# wpf xaml valueconverter

我正在尝试在 WPF 中绘制一些实体。我的集合包含 System.Drawing.Rectangle 对象,当我尝试在 WPF XAML 中访问这些对象的位置时,出现以下错误

无法创建默认转换器来执行类型“System.Drawing.Point”和“System.Windows.Point”之间的“单向”转换。考虑使用 Binding 的 Converter 属性

我知道我必须使用一些值转换器。您能指导我如何将“System.Drawing.Point”转换为“System.Windows.Point”吗?

更新:

以下代码给出了一些异常

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

XAML:

<PathFigure StartPoint= "{Binding BoundingRect.Location, Converter={StaticResource PointConverter}}">
Run Code Online (Sandbox Code Playgroud)

Sri*_*vel 7

我想你已经得到了InvalidCastException,你不能只是将一种类型转换为另一种类型,除非它们之间存在隐式或显式转换。请记住演员不同,转换也不同。以下代码System.Drawing.Point相互转换System.Windows.Point,反之亦然。

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

如果 aSystem.Drawing.Point来自 Windows 窗体鼠标事件,例如单击事件,则System.Drawing.Point不能System.Windows.Point以这种方式直接转换为 a,因为每个事件的坐标系可能不同。有关更多信息,请参阅/sf/answers/1385359601/ 。