【问题标题】:Converter of System.Drawing.Point' to 'System.Windows.PointSystem.Drawing.Point' 到 'System.Windows.Point 的转换器
【发布时间】:2014-04-03 03:40:06
【问题描述】:

我试图在 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}}">

【问题讨论】:

  • 为什么要投反对票?告诉我,我以后可以改正
  • 我是反对者,现在被删除了。原因是你没有展示你的尝试,只是问给我代码。在您的编辑问题看起来不错之后。
  • @SriramSakthivel,非常感谢。现在我明白了
  • 欢迎您,我的回答对您有帮助吗?如果有帮助,别忘了标记为答案

标签: c# wpf xaml valueconverter


【解决方案1】:

我猜你已经得到了InvalidCastException,你不能只将一种类型转换为另一种类型,除非它们之间存在隐式或显式转换。记住 cast 是不同的, convert 是不同的。以下代码将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窗体的鼠标事件,例如点击事件,则System.Drawing.Point不能通过这种方式直接转换为System.Windows.Point,因为每个的坐标系可能不同。请参阅https://stackoverflow.com/a/19790851/815724 了解更多信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-08
    • 2012-03-06
    • 1970-01-01
    • 1970-01-01
    • 2011-03-04
    • 1970-01-01
    相关资源
    最近更新 更多