你可以用绑定来做!
xml视图:
<ItemsControl ItemsSource="{Binding List}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Label Content="{Binding Value, Mode=TwoWay}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
在构造函数后面的代码中:
DataContext = new ViewModelClass();
在 ViewModelClass 中:
class ViewModelClass : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string name)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
private ObservableCollection<StringObject> _List = new ObservableCollection<StringObject>();
public ObservableCollection<StringObject> List
{
get { return _List; }
set
{
_List = value;
NotifyPropertyChanged("List");
}
}
public ViewModelClass()
{
List = new ObservableCollection<StringObject>
{
new StringObject {Value = "your"},
new StringObject {Value = "list"},
new StringObject {Value = "of"},
new StringObject {Value = "string"}
};
}
}
public class StringObject
{
public string Value { get; set; }
}
小心一个类型string
它不起作用的集合,你必须使用一个对象 =>StringObject