wpf - 将折线绑定到自定义 class

wpf - bind polyline to custom class

有谁知道是否可以将折线绑定到自定义对象集合?

例如,我有一个 class 像这样:

public class MyDataClass{
    public double Value { get; set; } //I'd like to map this to a polyline point's x value
    public double Position { get; set; } //I'd like to map this to a polyline point's y value
}

我想将折线绑定到这些对象的集合,并将 Value 属性转换为 X,将 Position 属性转换为 Y。

谢谢!

Polyline 需要 PointsPointCollection 才能绘制它们,您可以使用转换器来确保: Xaml

<Polyline Stretch="Fill" Grid.Column="0"
      Name="Polyline" Stroke="Red"
      Points="{Binding Points,Converter={StaticResource ToPointConverter}}">
    </Polyline>

转换器是这样实现的:

public class ToPointConverter:IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null) return null;            
        var pointCollection=new PointCollection();
        (value as List<MyDataClass>).ForEach(x=>{pointCollection.Add(new Point()
        {
            X = x.Value,
            Y = x.Position
        });});
        return pointCollection;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

并在您的代码隐藏或您的 Viewmodel 中定义 List<MyDataClass> 属性 :

public List<MyDataClass> Points { get; set; }

不要忘记在您的资源中设置 DataContextToPointConverter

`

虽然 Joseph 已经回答了,但我想添加一个更短、更灵活的 Convert 方法实现,它使用 LINQ Select 方法:

using System.Linq;
...

public object Convert(
    object value, Type targetType, object parameter, CultureInfo culture)
{
    var myDataCollection = value as IEnumerable<MyDataClass>;

    if (myDataCollection == null)
    {
        return null;
    }

    return new PointCollection(
        myDataCollection.Select(p => new Point(p.Value, p.Position)));
}