2012-03-13 25 views
11

Tôi có tài sản sau đây Temp2: (UserControl của tôi thực hiện INotifyPropertyChanged)bộ mã XAML ItemsSource = "{Binding}" với mã đằng sau

ObservableCollection<Person> _Temp2; 
    public ObservableCollection<Person> Temp2 
    { 
     get 
     { 
      return _Temp2; 
     } 
     set 
     { 
      _Temp2 = value; 
      OnPropertyChanged("Temp2"); 
     } 
    } 

    public event PropertyChangedEventHandler PropertyChanged = delegate { }; 

    private void OnPropertyChanged(string propertyName) 
    { 
     PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
    } 

tôi cần phải tạo ra một listview động. Tôi có listview sau trong XAML:

<ListView 
    Name="listView1" 
    DataContext="{Binding Temp2}" 
    ItemsSource="{Binding}" 
    IsSynchronizedWithCurrentItem="True"> 
<ListView.View> 
.... etc 

Bây giờ tôi đang cố gắng để tạo listview cùng với C# như:

 ListView listView1 = new ListView(); 
     listView1.DataContext = Temp2; 
     listView1.ItemsSource = Temp2; // new Binding(); // ????? how do I have to implement this line 
     listView1.IsSynchronizedWithCurrentItem = true; 
     //.. etc 

khi tôi cư listview với C# listview không được dân cư. tôi đang làm gì sai?

Trả lời

15

Bạn cần tạo đối tượng Binding.

Binding b = new Binding("Temp2") { 
    Source = this 
}; 
listView1.SetBinding(ListView.ItemsSourceProperty, b); 

Đối số được truyền cho hàm tạo là Path mà bạn đã quen thuộc từ liên kết XAML.

Bạn có thể bỏ qua PathSource nếu bạn đặt DataContext để Temp2 như bạn làm trên, nhưng cá nhân tôi nghĩ rằng nó thích hợp hơn để ràng buộc vào một ViewModel (hoặc nguồn dữ liệu khác) và sử dụng một Path hơn để ràng buộc trực tiếp đến một thành viên lớp học.

0
listView1.SetBinding(ListView.ItemsSourceProperty, new Binding()); 
+0

Không làm việc không biết tại sao? –

1

Bạn phải đặt một số thuộc tính của trường hợp Ràng buộc. Trong trường hợp của bạn, có thể nó sẽ giống như ...

listView1.SetBinding(ListView.ItemsSourceProperty, new Binding { Source = Temp2 }); 
Các vấn đề liên quan