我觉得很难制定我的问题,而且有可能某人已经回答了相同(或非常相似)的问题,但我一直在寻找一个小时而且无法继续我的项目。
我有一个名为Book
的课程:
namespace Book_Manager
{
public enum Rank { Worse = 1, Bad, Good, Super };
public class Book
{
public string title;
public string author;
public int pages;
public string publisher;
public Rank rank;
public string description;
public Book(string title, string author, int pages, string publisher, Rank rank, string description)
{
this.title = title;
this.author = author;
this.pages = pages;
this.publisher = publisher;
this.rank = rank;
this.description = description;
}
}
}
这是我的MainWindow
课程:
namespace Book_Manager
{
public partial class MainWindow : Window
{
public ObservableCollection<Book> books;
public MainWindow()
{
InitializeComponent();
books = new ObservableCollection<Book>();
myListBox.DataContext = books;
for (int i = 0; i < 4; i++)
{
var bk = new Book("test", "test", 100, "test", Rank.Bad, "test");
books.Add(bk);
}
}
}
}
现在,我希望myListBox
列出books
集合的内容。我已经在Window.Resources中为myListBox
创建了一个自定义DataTemplate,但我不知道如何将Book字段传递到相应的Content属性中:
<Window.Resources>
<DataTemplate x:Key="MmuhTemplate">
<Grid Background="White">
<Label Content="Something like Book.author"/>
<Label Content="How do I do it?"/>
</Grid>
</DataTemplate>
</Window.Resources>
我已经在Window中声明了xmlns:local="clr-namespace:Book_Manager"
。现在怎么办?
答案 0 :(得分:1)
而不是DataContext
,尝试设置ListBox
&#39; s ItemsSource
:
myListBox.ItemsSource = books;
使用模型中的公共属性代替字段/成员:
public class Book
{
public string author { get; set; }
........
........
}
然后在<DataTemplate>
绑定到相应的属性:
<DataTemplate x:Key="MmuhTemplate">
<Grid Background="White">
<Label Content="{Binding author}"/>
<Label Content="{Binding propertyName}"/>
</Grid>
</DataTemplate>
上面的简单绑定应该解决得很好,因为ListBoxItem
数据上下文默认设置为ItemsSource
中的相应项。