WPF:链接数据模板标签与集合元素'属性

本文关键字:元素 集合 属性 标签 链接 数据 WPF | 更新日期: 2023-09-27 18:01:48

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

我有一个类叫做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集合的内容。我已经在窗口中为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>

我已经在窗口中声明了xmlns:local="clr-namespace:Book_Manager"。现在该做什么?

WPF:链接数据模板标签与集合元素'属性

DataContext改为ListBoxItemsSource:

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中的相应项。