简体   繁体   English

在 WPF 中使用带有 ItemSource 和绑定的自定义 class

[英]Using a custom class with ItemSource and Binding in WPF

I'm working on a project to extract Adobe Creative Cloud fonts to another directory so they can be used in external programs that don't recognize them.我正在开发一个项目,将 Adobe Creative Cloud fonts 提取到另一个目录,以便它们可以在无法识别它们的外部程序中使用。 I would like to populate an Extended WPF Toolkit CheckListBox with the names of the fonts I've scraped from the Adobe directory.我想用我从 Adobe 目录中抓取的CheckListBox的名称填充扩展的 WPF 工具包 CheckListBox。 However, I've created a custom class to hold the data I need.但是,我创建了一个自定义 class 来保存我需要的数据。 It's a little hard to explain without the code so here goes.如果没有代码,这有点难以解释,所以就到这里吧。

// custom Font class
public class Font
{
    public string FontName { get; set; }
    public string FontPath { get; set; }
    public bool IsChecked { get; set; }
}

// list of fonts to be bound to the CheckListBox
public List<Font> fontItems;

// function that appends items to the list
private void retrieveFonts_Click(object sender, RoutedEventArgs e)
{
    ...
    Font font = new Font
    {
        FontName = fontName,
        FontPath = fontPath,
        IsChecked = true
    }
    fontItems.Add(font)
}
<!--CheckListBox with my best guess for the binding-->
<xctk:CheckListBox
    Name="listFontBox"
    Grid.Row="0"
    IsSelectAllActive="False"
    ItemsSource="{Binding fontItems.FontName}">
</xctk:CheckListBox>

I've tried looking at threads on SO and on other external websites and none of the code seems to work on modern day WPF.我试过查看 SO 和其他外部网站上的线程,但似乎没有任何代码在现代 WPF 上有效。

How can I get the CheckBoxList to populate with a list of all the FontName properties of the Font objects?如何让CheckBoxList填充Font对象的所有FontName属性的列表? Is this possible at all?这可能吗?

First binding generally doesn't work to fields.第一次绑定通常不适用于字段。 Change the fontItems field to property.fontItems字段更改为属性。 If you want to populate your list better way is to use ObservableCollection .如果你想填充你的列表,更好的方法是使用ObservableCollection

public ObservableCollection<Font> fontItems { get;set; } 

Bind it to CheckListBox and set DisplayMemberPath .将其绑定到 CheckListBox 并设置DisplayMemberPath

<xctk:CheckListBox DisplayMemberPath="FontName"
                   Grid.Row="0"
                   SelectedMemberPath="IsChecked"
                   IsSelectAllActive="False"
                   ItemSource="{Binding fontItems}" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM