有谁知道是否可以将折线绑定到自定义对象的集合?
例如,我有一个类似的类:
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.
谢谢!
答案 0 :(得分:1)
虽然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)));
}
答案 1 :(得分:0)
Polyline
期待PointCollection
Points
为了绘制它们,您可以使用转换器来确保:
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; }
不要忘记设置DataContext
并在资源中设置ToPointConverter
。
`