【问题标题】:Using a custom class with ItemSource and Binding in WPF [duplicate]在WPF中使用带有ItemSource和Binding的自定义类[重复]
【发布时间】:2022-01-16 15:51:25
【问题描述】:

我正在开展一个项目,将 Adob​​e Creative Cloud 字体提取到另一个目录,以便它们可以在无法识别它们的外部程序中使用。我想用我从 Adob​​e 目录中抓取的字体名称填充扩展 WPF 工具包CheckListBox。但是,我创建了一个自定义类来保存我需要的数据。没有代码有点难以解释,所以这里。

// 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>

我尝试查看 SO 和其他外部网站上的线程,但似乎没有任何代码在现代 WPF 上运行。

如何让CheckBoxList 填充Font 对象的所有FontName 属性的列表?这可能吗?

【问题讨论】:

    标签: c# wpf wpftoolkit


    【解决方案1】:

    第一次绑定通常不适用于字段。将fontItems 字段更改为属性。如果您想填充您的列表,更好的方法是使用ObservableCollection

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

    将其绑定到 CheckListBox 并设置DisplayMemberPath

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-18
      • 2016-02-29
      • 1970-01-01
      • 2017-03-02
      • 1970-01-01
      • 2016-05-05
      相关资源
      最近更新 更多