14

I have the following property Temp2: (my UserControl implements INotifyPropertyChanged)

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

I need to create a listview dynamically. I have the following listview in XAML:

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

Now I am trying to create the same listview with c# as:

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

when I populate the listview with C# the listview does not get populated. what am I doing wrong?

Tono Nam
  • 34,064
  • 78
  • 298
  • 470

3 Answers3

22

You need to create a Binding object.

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

The argument passed to the constructor is the Path that you're used to from XAML bindings.

You can leave out the Path and Source if you set the DataContext to Temp2 as you do above, but I personally think it's preferable to bind to a ViewModel (or other data source) and use a Path than to directly bind to a class member.

kitti
  • 14,663
  • 31
  • 49
2

You have to set some properties of the Binding instance. In your case it will probably be something like...

listView1.SetBinding(ListView.ItemsSourceProperty, new Binding { Source = Temp2 });
-1
listView1.SetBinding(ListView.ItemsSourceProperty, new Binding());
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964