2009-05-15 8 views
4

포인트 목록이 포함 된 ViewModel 클래스가 있는데이를 Polyline에 바인딩하려고합니다. Polyline은 초기 포인트 목록을 선택하지만 INotifyPropertyChanged를 구현하더라도 추가 점이 추가되면이를 알지 못합니다. 뭐가 문제 야?이 데이터 바인딩이 작동하지 않는 이유는 무엇입니까?

<StackPanel> 
    <Button Click="Button_Click">Add!</Button> 
    <Polyline x:Name="_line" Points="{Binding Pts}" Stroke="Black" StrokeThickness="5"/> 
</StackPanel> 

C#을 측면 : 컬렉션에 바인딩되어 있기 때문에, 그것은 ObservableCollection<T> 뭔가를해야한다는 매우 가능성이

// code-behind 
_line.DataContext = new ViewModel(); 
private void Button_Click(object sender, RoutedEventArgs e) 
{ 
    // The problem is here: NOTHING HAPPENS ON-SCREEN! 
    ((ViewModel)_line.DataContext).AddPoint(); 
} 

// ViewModel class 
public class ViewModel : INotifyPropertyChanged 
{ 
    public event PropertyChangedEventHandler PropertyChanged; 

    public PointCollection Pts { get; set; } 

    public ViewModel() 
    { 
     Pts = new PointCollection(); 
     Pts.Add(new Point(1, 1)); 
     Pts.Add(new Point(11, 11)); 
    } 

    public void AddPoint() 
    { 
     Pts.Add(new Point(25, 13)); 
     if (PropertyChanged != null) 
      PropertyChanged(this, new PropertyChangedEventArgs("Pts")); 
    } 
} 
+0

답변이 업데이트되어 원인을 찾았습니다. – Carlo

답변

1
는 종속성 속성에 PointCollections 속성을 변경

:

public PointCollection Pts 
     { 
      get { return (PointCollection)GetValue(PtsProperty); } 
      set { SetValue(PtsProperty, value); } 
     } 

     // Using a DependencyProperty as the backing store for Pts. This enables animation, styling, binding, etc... 
     public static readonly DependencyProperty PtsProperty = 
      DependencyProperty.Register("Pts", typeof(PointCollection), typeof(ViewModel), new UIPropertyMetadata(new PointCollection())); 

가 BTW 이렇게, 당신은하여 PropertyChanged 이벤트를 해고 할 필요가 없습니다.

아 죄송합니다, 당신의 목적은 DependencyObject에

public class ViewModel : DependencyObject 
{ 
//... 
} 
+0

일반적으로 ViewModel을 DependencyObjects로 구현하는 것은 권장하지 않습니다. DependencyObjects는 POCO가 INotifyPropertyChanged를 구현하는 것보다 훨씬 무겁습니다. 어쨌든 아무 것도 변경하지 않습니다. –

+0

감사합니다. 대답을 테스트 했습니까? INotifyPropertyChanged를 사용하면 포인트 콜렉션이 아닌 다른 속성에 사용할 때 유용합니다. – Qwertie

+0

그래, Pts.Add (새로운 포인트 (25, 13)) 대신 포인트를 만들 때 코드를 변경했습니다. 나는 Pts.Add (새로운 포인트 (random.Next (0,100), random.Next (0,100))); 모든 새로운 랜덤 포인트가 생성되어 화면에 표시됩니다. – Carlo

4

. PointCollection에서 ObservableCollection<Point>으로 전환하면 어떻게됩니까?

+0

방금 ​​동일한 시나리오를 테스트했지만 바인딩 자체가 작동합니다 (Points 속성에 새 포인트가 포함됨) ...하지만 어떤 이유로 PolyLine이 업데이트되지 않습니다 –

+0

Thomas, 매우 흥미 롭습니다. – Qwertie

+0

ObservableCollection 이 작동하지 않습니다. 초기 라인조차도 화면에 나타나지 않습니다. 분명히 Polyline은 ObservableCollection 에 대한 바인딩을 지원하지 않으며 List 을 지원하지 않습니다. – Qwertie

1

에서 내가 대신에서 INotifyPropertyChanged의 INotifyCollectionChanged를 구현하여 POCO로 작동있어 상속 할 필요가있다.

관련 문제