2012-03-13 13 views
11

ho la seguente proprietà Temp2: (il mio UserControl implementa INotifyPropertyChanged)set XAML ItemsSource = "{Binding}" con il codice dietro

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)); 
    } 

Ho bisogno di creare un controllo ListView in modo dinamico. Ho il seguente listview in XAML:

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

Ora sto cercando di creare lo stesso ListView con C# come:

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

quando io popolo ListView con C# ListView non viene popolata. Che cosa sto facendo di sbagliato?

risposta

15

È necessario creare un oggetto Binding.

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

L'argomento passato al costruttore è la Path che siete abituati a da attacchi XAML.

Puoi lasciare fuori la Path e Source se si imposta la DataContext a Temp2 come si fa sopra, ma io personalmente penso che sia preferibile legarsi a un ViewModel (o altra fonte di dati) e utilizzare un Path rispetto di legarsi direttamente a un membro della classe.

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

Non ha funzionato non so perché? –

1

È necessario impostare alcune proprietà dell'istanza Binding. Nel tuo caso sarà probabilmente qualcosa come ...

listView1.SetBinding(ListView.ItemsSourceProperty, new Binding { Source = Temp2 }); 
Problemi correlati