[英]C# WPF DataTemplate binding
我將MyListBox
綁定到MyObject實例列表。 MyObject包含一個名為TextField的字符串字段。 我想將listBox中的每個項目綁定到MyObject.TextField
。 我的代碼如下,但是它不起作用。
<ListBox Name="MyListBox">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=TextField}"></TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
這樣做的正確方法是什么?
解決:我的物件類別的TextField不是屬性
確保設置ListBox的ItemsSource :
<ListBox Name="MyListBox" ItemsSource="{Binding theList}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding TextField}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
編輯:我嘗試了VS 2010中的解決方案...這是代碼
首先,您創建自己的班級,例如人班
class Person
{
public Person(String name)
{
this.name = name;
}
String name;
public String Name
{
get { return name; }
set { name = value; }
}
}
然后像這樣在xaml中創建列表框
<ListBox Height="222" HorizontalAlignment="Left" Margin="105,28,0,0" Name="listBox1" VerticalAlignment="Top" Width="120" ItemsSource="{Binding}" >
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=Name}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
xaml中的note注釋Path = Name是要在列表框中顯示的屬性
在文件后面的代碼中,輸入以下代碼
List<Person> persons = new List<Person>();
persons.Add(new Person("person 1"));
persons.Add(new Person("person 2"));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.