使用代码设置xaml代码ItemsSource ="{Binding}"

Ton*_*Nam 14 c# datacontext inotifypropertychanged itemssource

我有以下属性Temp2:(我的UserControl实现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));
    }
Run Code Online (Sandbox Code Playgroud)

我需要动态创建一个列表视图.我在XAML中有以下列表视图:

<ListView 
     Name="listView1" 
     DataContext="{Binding Temp2}" 
     ItemsSource="{Binding}" 
     IsSynchronizedWithCurrentItem="True">
 <ListView.View>
 .... etc
Run Code Online (Sandbox Code Playgroud)

现在我尝试用c#创建相同的listview:

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

当我使用C#填充listview时,listview不会被填充.我究竟做错了什么?

Rya*_*n P 20

您需要创建一个Binding对象.

Binding b = new Binding( "Temp2" ) {
    Source = this
};
listView1.SetBinding( ListView.ItemsSourceProperty, b );
Run Code Online (Sandbox Code Playgroud)

传递给构造函数的参数是Path您习惯使用的XAML绑定.

你可以省略Path,Source如果你像上面那样设置DataContextto Temp2,但我个人认为最好绑定到ViewModel(或其他数据源)并使用Paththan来直接绑定到类成员.