2

我们如何在运行时向 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 Name="NotesList" Background="WhiteSmoke">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Title, Mode=TwoWay}" />
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
4

3 回答 3

1

你将不得不做一些不同的事情,你不能只是将所有属性分配给 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);
于 2012-09-17T16:59:49.757 回答
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;
}
于 2012-09-17T17:11:14.227 回答
0

我设法弄清楚如何做到这一点:

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

于 2012-09-17T17:23:24.910 回答