繁体   English   中英

在代码隐藏中添加ListBoxItems

[英]Adding ListBoxItems in Code-behind

我们如何在运行时将新项目添加到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>

您将不得不做一些不同的事情,您不能仅将所有属性分配给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);
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;
}

我设法弄清楚怎么做:

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

暂无
暂无

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

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