set xaml code ItemsSource="{Binding}" with code behind

Tono Nam picture Tono Nam · Mar 13, 2012 · Viewed 20.4k times · Source

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?

Answer

Ryan P picture Ryan P · Mar 13, 2012

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.