C# WPF:将数据模板标签与集合元素链接';性质

C# WPF:将数据模板标签与集合元素链接';性质,c#,wpf,C#,Wpf,我发现很难阐述我的问题,可能有人已经回答了相同(或非常相似)的问题,但我已经找了一个小时,无法继续我的项目 我有一门课叫Book: namespace Book_Manager { public enum Rank { Worse = 1, Bad, Good, Super }; public class Book { public string title; public string author; public in

我发现很难阐述我的问题,可能有人已经回答了相同(或非常相似)的问题,但我已经找了一个小时,无法继续我的项目

我有一门课叫
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;
        }
    }
}
这是我的
主窗口
类:

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);
            }
        }
    }
}

我已经在窗口中声明了
xmlns:local=“clr namespace:Book\u Manager”
。现在怎么办?

请尝试设置
列表框的
项目资源,而不是
DataContext

myListBox.ItemsSource = books;
在模型中使用公共属性,而不是字段/成员:

public class Book
{
    public string author { get; set; }
    ........
    ........
}
然后在
中绑定到相应的属性:

<DataTemplate x:Key="MmuhTemplate">
    <Grid Background="White">
        <Label Content="{Binding author}"/>
        <Label Content="{Binding propertyName}"/>
    </Grid>
</DataTemplate>


上面的简单绑定应该可以解决,因为默认情况下,
ListBoxItem
数据上下文设置为
ItemsSource
中的相应项。

非常有效,谢谢。但是,为什么我应该在
Book
类中使用属性而不是常规成员?稍后我将实现XML序列化,这不会导致任何错误吗?
<DataTemplate x:Key="MmuhTemplate">
    <Grid Background="White">
        <Label Content="{Binding author}"/>
        <Label Content="{Binding propertyName}"/>
    </Grid>
</DataTemplate>