【问题标题】:Adding ListBoxItems in Code-behind在代码隐藏中添加 ListBoxItems
【发布时间】:2012-09-17 16:53:52
【问题描述】:

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

【问题讨论】:

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


【解决方案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);

【讨论】:

  • Metro 应用程序中没有可用于 ListBox 的DataSource
  • 第二个选项显示“值不在预期范围内”异常。
【解决方案2】:
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;
}

【讨论】:

  • 对不起,我也试过了。不过谢谢你的帮助。
  • 您使用的是 WPF 还是 Winforms。如果是 WPF,那么它是不同的绑定方式。
  • Metro 风格应用程序中的 Xaml;参考问题标签。您不会在 WinForms 中获得 XAML。
  • .net winform 没有 xaml 只有 wpf 有 xaml
【解决方案3】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-02
    • 1970-01-01
    相关资源
    最近更新 更多