如何在运行时向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>发布于 2012-09-18 01:23:25
我设法弄明白了怎么做:
notes.Insert(0, new NoteView { a = "Untitled note", b = "", c = "" });
发布于 2012-09-18 00:59:50
YOu必须做一些不同的事情,你不能仅仅把所有的属性都指定给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-18 01:11:14
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;
}https://stackoverflow.com/questions/12463853
复制相似问题