我有以下属性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));
}
我需要动态创建一个列表视图。我在XAML中有以下列表视图:
<ListView
Name="listView1"
DataContext="{Binding Temp2}"
ItemsSource="{Binding}"
IsSynchronizedWithCurrentItem="True">
<ListView.View>
.... etc
现在我正试图用c#创建相同的列表视图,如下所示:
ListView listView1 = new ListView();
listView1.DataContext = Temp2;
listView1.ItemsSource = Temp2; // new Binding(); // ????? how do I have to implement this line
listView1.IsSynchronizedWithCurrentItem = true;
//.. etc
当我用C#填充列表视图时,列表视图不会被填充。我做错了什么?
您需要创建一个Binding
对象。
Binding b = new Binding( "Temp2" ) {
Source = this
};
listView1.SetBinding( ListView.ItemsSourceProperty, b );
传递给构造函数的参数是用于XAML绑定的Path
。
如果像上面那样将DataContext
设置为Temp2
,则可以省略Path
和Source
,但我个人认为绑定到ViewModel(或其他数据源)并使用Path
比直接绑定到类成员更可取。
您必须设置Binding实例的一些属性。在你的情况下,可能会是。。。
listView1.SetBinding(ListView.ItemsSourceProperty, new Binding { Source = Temp2 });
listView1.SetBinding(ListView.ItemsSourceProperty, new Binding());