Converter of System.Drawing.Point' to 'System.Windows.Point

巧了我就是萌 提交于 2020-01-05 03:18:15

问题


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

Cannot create default converter to perform 'one-way' conversions between types 'System.Drawing.Point' and 'System.Windows.Point'. Consider using Converter property of Binding

I know I have to use some valueconverter. Could you please guide me how to convert System.Drawing.Point' to'System.Windows.Point?

Update:

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}}">

回答1:


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

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.



来源:https://stackoverflow.com/questions/22827412/converter-of-system-drawing-point-to-system-windows-point

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!