2013-03-15 208 views
2

我想在我的UserControl中有一個圖形部分,它將根據集合顯示行(並在運行時更新座標,並在運行時基於集合添加/刪除行)。將ObservableCollection綁定到行

讓我們假設我有一個名爲Class 1類:

public class Class1 : INotifyPropertyChanged 
    { 
     public event PropertyChangedEventHandler PropertyChanged; 
     public void OnPropertyChanged(PropertyChangedEventArgs e) 
     { 
      if (PropertyChanged != null) 
       PropertyChanged(this, e); 
     } 

     private int _x1 = 0; 
     public int X1 
     { 
      get { return _x1; } 
      set 
      { 
       _x1 = value; 
       OnPropertyChanged(new PropertyChangedEventArgs("X1")); 
      } 
     } 
    } 

在我的用戶而一個ObservableCollection:

 public event PropertyChangedEventHandler PropertyChanged; 
     public void OnPropertyChanged(PropertyChangedEventArgs e) 
     { 
      if (PropertyChanged != null) 
       PropertyChanged(this, e); 
     } 

     private ObservableCollection<Class1> _classes = new ObservableCollection<Class1>(); 
     public ObservableCollection<Class1> Classes 
     { 
      get { return _classes; } 
     } 

如果我知道線的量,我可以在創建的行數我的用戶控件是這樣的:

XAML:

<Grid DataContext="{Binding ElementName=LayoutRoot}"> 
<Line X1="{Binding Items[0].X1}" X2="100" Y1="50" Y2="100" Stroke="Red" StrokeThickness="4"/> 
<Line X1="{Binding Items[1].X1}" ... /> 
... 
</Grid> 

我該如何繼續?

感謝您的努力

回答

2

你可以使用一個ItemsControl併爲Class1對象DataTemplate和綁定您ObservableCollectionItemsControl

它也可能是一個好主意,用CanvasItemsPanelTemplate,如果你想畫線所有的地方

下面是一個簡單的例子:

的XAML:

<Grid DataContext="{Binding ElementName=UI}"> 
    <ItemsControl ItemsSource="{Binding Classes}"> 
     <ItemsControl.ItemsPanel> 
      <ItemsPanelTemplate> 
       <Canvas /> 
      </ItemsPanelTemplate> 
     </ItemsControl.ItemsPanel> 
     <ItemsControl.ItemTemplate> 
      <DataTemplate DataType="{x:Type local:Class1}"> 
       <Line Stroke="Black" StrokeThickness="2" Fill="Black" X1="{Binding X1}" X2="{Binding X2}" Y1="{Binding Y1}" Y2="{Binding Y2}" /> 
      </DataTemplate> 
     </ItemsControl.ItemTemplate> 
    </ItemsControl> 
</Grid> 

代碼:

public partial class MainWindow : Window 
{ 

    public MainWindow() 
    { 
     InitializeComponent(); 
     Random ran = new Random(); 
     for (int i = 0; i < 10; i++) 
     { 
      Classes.Add(new Class1 { X1 = ran.Next(0,100), Y1 = ran.Next(0,100), X2 = ran.Next(0,100), Y2 = ran.Next(0,100) }); 
     } 
    } 

    private ObservableCollection<Class1> _classes = new ObservableCollection<Class1>(); 
    public ObservableCollection<Class1> Classes 
    { 
     get { return _classes; } 
    } 

} 

結果:

enter image description here

1

您可以使用ItemsControl作爲容器來顯示您的行。

<ItemsControl DataContext="{Binding ElementName=LayoutRoot}" 
       ItemsSource={Binding}> 
    <ItemsControl.ItemTemplate> 
    <DataTemplate> 
     <Line X1="{Binding Items[0].X1}" X2="100" Y1="50" Y2="100" Stroke="Red" StrokeThickness="4"/> 
    </DataTemplate> 
    </ItemsControl.ItemTemplate> 
</ItemsControl> 
相關問題