简体   繁体   English

如何使用 AvaloniaUI 在 ComboBox 中动态加载项目

[英]How to dynamically load items in a ComboBox using AvaloniaUI

I have a ComboBox in AvaloniaUI, and I want to load the list dynamically based off the names provided by an array of another class.我在 AvaloniaUI 中有一个 ComboBox,我想根据另一个 class 的数组提供的名称动态加载列表。 For example, take the following code:例如,采用以下代码:

<ComboBox Name="Select" SelectedIndex="0"></ComboBox>
public class MainWindow : Window
{
    private Note[] notes;
    public MainWindow()
    {
        InitializeComponent();
    }

    private void InitializeComponent()
    {
        AvaloniaXamlLoader.Load(this);
        notes = Utility.GetNotes();

        ComboBox comboBox = this.Find<ComboBox>("Select");
        foreach (Note n in notes)
        {
            comboBox.Items.Add(
                new ComboBoxItem()
                {
                    Content = n.Name
                }
            );
        }
    }
}
public class Note
{
    public string Name;
    public string NoteText;
}

I'm not sure of the proper way to do this in AvaloniaUI since in WPF you could just directly call that comboBox.Items.Add() function.我不确定在 AvaloniaUI 中执行此操作的正确方法,因为在 WPF 您可以直接调用comboBox.Items.Add() ZC1C425268E68385D1AB5074C17A94F However that function doesn't seem to exist when using AvaloniaUI.但是,使用 AvaloniaUI 时似乎不存在 function。

Following @kekekeks comment above I was able to make this work with a few changes:在上面的@kekekeks评论之后,我能够通过一些更改来完成这项工作:

<ComboBox Name="Select">
    <ComboBox.ItemTemplate>
      <DataTemplate>
        <TextBlock Text="{Binding Name}" />
      </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>
public class MainWindow : Window
{
    private List<Note> Notes;
    public MainWindow()
    {
        InitializeComponent();
    }

    private void InitializeComponent()
    {
        AvaloniaXamlLoader.Load(this);
        Notes = Utility.GetNotes();
        ComboBox comboBox = this.Find<ComboBox>("Select");
        comboBox.Items = Notes;
        comboBox.SelectedIndex = 0;
    }
}
public class Note
{
    public string Name { get; set; }
    public string NoteText { get; set; }
}

I just want to add that having the Notes variable as an array doesn't seem to work, so I had to change it to a list and I had to change the Note class to use { get; set; }我只想补充一点,将 Notes 变量作为数组似乎不起作用,因此我不得不将其更改为列表,并且必须将 Note class 更改为使用{ get; set; } { get; set; } { get; set; } as well. { get; set; }也是如此。

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

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