将 'System.Drawing.Point' 转换为 'System.Windows.Point' 的转换器

3
我正在尝试在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();
    }
}

XAML:
<PathFigure StartPoint= "{Binding BoundingRect.Location, Converter={StaticResource PointConverter}}">

为什么会有负面评价呢?请告诉我,我可以在未来进行改正。 - RobinAtTech
我是之前的踩贴者,现在已经取消了。原因是你没有展示你的尝试,只是直接要求给你代码。在你编辑后,问题看起来不错。 - Sriram Sakthivel
@SriramSakthivel,非常感谢。现在我明白了。 - RobinAtTech
欢迎,我的回答有帮助吗?如果有帮助,请不要忘记将其标记为答案。 - Sriram Sakthivel
1个回答

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);
    }
}

如果 System.Drawing.Point 来自于 Windows Forms 鼠标事件,比如点击事件,那么不能直接按照这种方式将其转换为 System.Windows.Point,因为它们的坐标系统可能不同。更多信息请参见https://dev59.com/S2855IYBdhLWcg3wpmDw#19790851

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接