[英]set xaml code ItemsSource=“{Binding}” with code behind
我有以下属性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:
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#填充listview时,listview不会被填充。 我究竟做错了什么?
您需要创建一个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());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.