[英]Data Binding an observable collection of strings
I have the following class: 我有以下课程:
public class MyClass
{
public ObservableCollection<string> MyList { get; set; }
public string MyListTitle { get; set; }
...
I'm populating it as follows: 我将其填充如下:
MyClass myClass = new MyClass("Data"); // Populates title
myClass.MyList.Add("Test data 1");
myClass.MyList.Add("Test data 2");
myListView.DataContext = MyClass.MyList;
Finally, here's the XAML: 最后,这是XAML:
<ListView Visibility="Visible" x:Name="myListView" Height="Auto">
<ScrollViewer x:Name="contentScrollView">
<TextBlock x:Name="DataItem" Text="{Binding}" />
</ScrollViewer>
</ListView>
The result (and problem) is that I get the class name displayed once in the listview, rather than the two entries above. 结果(和问题)是我在列表视图中一次显示了类名,而不是上面的两个条目。
You first need to set the ItemsSource
property of the ListView
to your ObservableCollection
您首先需要将
ListView
的ItemsSource
属性设置为ObservableCollection
myListView.ItemsSource = myClass.MyList;
Also, you need to use a DataTemplate to display the actual items: 另外,您需要使用DataTemplate来显示实际项目:
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock x:Name="DataItem" Text="{Binding}" />
</DataTemplate>
</ListView.ItemTemplate>
You're binding the TextBlock that's why you receive the .ToString() of the list. 您正在绑定TextBlock,这就是为什么您会收到列表的.ToString()的原因。 What you need to bind is the ItemsSource of your list, that way the ListView will bind its items with the ones inside your list.
您需要绑定的是列表的ItemsSource ,这样ListView会将其项目与列表中的项目绑定。
Possibly this one 可能这一个
myListView.DataContext = MyClass.MyList;
Shall become 成为
myListView.DataContext = myClass.MyList; //note the case of myClass
It should be 它应该是
<ListView x:Name="myListView" Height="Auto" ItemsSource="{Binding MyList}">
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock x:Name="DataItem" Text="{Binding}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
and 和
MyClass myClass = new MyClass();
myClass.MyList = new ObservableCollection<string>();
myClass.MyList.Add("Test data 1");
myClass.MyList.Add("Test data 2");
this.DataContext = myClass;
and 和
public class MyClass
{
public ObservableCollection<string> MyList { get; set; }
public string MyListTitle { get; set; }
public MyClass()
{
}
}
Result 结果
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.