gpt4 book ai didi

c# - 在代码隐藏中添加 ListBoxItems

转载 作者:太空宇宙 更新时间:2023-11-03 16:26:19 25 4
gpt4 key购买 nike

我们如何在运行时向 Windows Metro 风格应用程序中的 ListBox 控件添加新项目?

我来自 WinForms,所以你可以想象,我现在很困惑。

我有以下内容:

public class NoteView
{
public string Title { get; set; }
public string b { get; set; }
public string c { get; set; }
}

然后:

List<NoteView> notes = new List<NoteView>();

protected void Button1_Click(object sender, RoutedEventArgs e)
{
notes.Add(new NoteView {
a = "text one",
b = "whatevs",
c = "yawns"
});

NotesList.ItemsSource = notes;
}

这是没用的。它什么都不做。此外,“输出”窗口中没有任何内容。没有错误,没有异常;什么都没有。

所以,然后我尝试直接添加到列表框:

NotesList.Items.Add("whatever!");

再次,什么也没发生。所以我尝试添加 UpdateLayout(); 但这也没有帮助。

有人知道这是怎么回事吗?

我们如何向 XAML ListBox 添加新项?

更新:

        <ListBox Name="NotesList" Background="WhiteSmoke">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Title, Mode=TwoWay}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

最佳答案

你必须做一些不同的事情,你不能把所有的属性都分配给列表框。所以创建这种类:

 public class NoteView
{
public string Item { get; set; }
public int Value { get; set; }
}

然后这是按钮点击事件中的代码:

        List<NoteView> notes = new List<NoteView>();
notes.Add(new NoteView { Item = "a", Value = 1 });
notes.Add(new NoteView { Item = "b", Value = 2 });
notes.Add(new NoteView { Item = "c", Value = 3 });

listBox1.DataSource = notes;
listBox1.DisplayMember = "Item";
listBox1.ValueMember = "Value";

--否则,如果您打算使用与您创建的相同的类,那么您可以这样做:

        List<NoteView> notes = new List<NoteView>();
notes.Add(new NoteView
{
a = "text one",
b = "whatevs",
c = "yawns"
});

listBox1.Items.Add(notes[0].a);
listBox1.Items.Add(notes[0].b);
listBox1.Items.Add(notes[0].c);

关于c# - 在代码隐藏中添加 ListBoxItems,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12463853/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com