在代码隐藏中添加ListBoxItems

时间:2012-09-17 16:53:53

标签: c# .net xaml listbox microsoft-metro

我们如何在运行时向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;
}

哪个没用。它什么都不做。此外,“输出”窗口中没有任何内容。没有错误,没有例外;什么都没有。

所以,然后我尝试直接添加到ListBox:

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>

3 个答案:

答案 0 :(得分:0)

你必须以不同的方式做到这一点,你不能只是将所有属性设置为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);

答案 1 :(得分:0)

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.DisplayMember = "a";
        NotesList.ValueMember = "b";
   NotesList.ItemsSource = notes;
}

答案 2 :(得分:0)

我设法弄明白该怎么做:

notes.Insert(0, new NoteView { a = "Untitled note", b = "", c = "" });