簡體   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