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

RobinAtTech picture RobinAtTech · Apr 3, 2014 · Viewed 11.3k times · Source

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

Answer

Sriram Sakthivel picture Sriram Sakthivel · Apr 3, 2014

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.