2015-01-09 3 views
0

폴리 라인을 사용자 정의 객체의 컬렉션에 바인딩 할 수 있는지 여부를 아는 사람이 있습니까?wpf - 폴리 라인을 사용자 정의 클래스에 바인딩

예를 들어, 나는 수업과 같이 있습니다

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 
} 

그리고 나는 그 개체의 컬렉션에 폴리 라인을 결합하여 X에 Value 속성와 Y에 위치 속성을 번역하고 싶습니다

감사합니다. 컨버터가과 같이 구현됩니다 XAML

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

:

답변

0

Polyline 것을 보장하기 위해 당신이 변환기를 사용할 수 그들을 잡아하기 위해 PointsPointCollection을 기대하고있다

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을 리소스에 설정하는 것을 잊지 마십시오.

`이미 조셉 응답 있지만

+0

감사합니다. 전체 컬렉션에서 변환기를 사용할 수 있다는 것을 알지 못했습니다. – user2424495

1

, 나는 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))); 
} 
관련 문제