【问题标题】:How to add things to a ListBox after setting its DataBinding?设置 DataBinding 后如何向 ListBox 添加内容?
【发布时间】:2014-10-08 20:45:57
【问题描述】:

我正在创建一个 Windows Phonw 8.1 应用程序。我有一个 ListBox,当我单击一个按钮时,我想在运行时附加/插入其他的。但它不起作用或崩溃。

我页面的构造函数有这个:

myData = new List<Stuff>() {
    new Stuff(){Name="AAA"},
    new Stuff(){Name="BBB"},
    new Stuff(){Name="CCC"},
    new Stuff(){Name="DDD"},
};
myListBox.DataContext = myData;

我的页面的 xaml:

<ListBox x:Name="myListBox" ItemsSource="{Binding}" Background="Transparent">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Name}" FontSize="20" Foreground="Red"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

好的,这很好,当我启动应用程序时,我可以看到包含 4 个项目的列表。

private void Button_Tapped(object sender, TappedRoutedEventArgs e)
{
    myData.Add(new Stuff() { Name = String.Format("Added item #{0}", myData.Count) });

    //I tried to set the DataContext again, but it does nothing
    myListBox.DataContext = mydata;

    //I tried to tell the the list to redraw itself, in winform, the Invalidate() method usually get the job done, so I tried both
    myListBox.InvalidateMeasure()
    //and / or
    myListBox.InvalidateArrange();
    //or
    myListBox.UpdateLayout();

    //I tried
    myListBox.Items.Add("Some text");
    //or
    myListBox.Items.Add(new TextBlock(){Text="Some text"});
    //or 
    (myListBox.ItemsSource as List<Stuff>).Add(new Stuff(){Name="Please work..."});
}

最好的办法就是抛出一个异常:

An exception of type 'System.Exception' occurred in mscorlib.ni.dll but was not handled in user code

Additional information: Catastrophic failure (Exception from HRESULT: 0x8000FFFF (E_UNEXPECTED))

我也使用了 ListView,但没有任何变化。额外问题:ListBox 和 ListView 有什么区别?

Google 并没有真正提供帮助,我发现的东西可能适用于旧版本的 Windows Phone 或普通 WPF 或 ASP.Net...

另外,发生的一件奇怪的事情是在将一个项目添加到列表后没有任何反应,当我点击一个旧项目时,我遇到了灾难性的失败。我的列表项上还没有活动。

我即将放弃数据绑定,而只是逐段代码构建我的应用程序。将东西添加到列表中应该不难,我做错了什么?

【问题讨论】:

  • 试试ObservableCollection&lt;T&gt; 而不是List&lt;T&gt;

标签: c# xaml windows-phone-8.1


【解决方案1】:

需要用INotifyPropertyChanged 接口实现一些东西,要么自己做,要么使用内置它的类。

MSDN INotifyPropertyChanged Interface

试试

using System.ComponentModel;
using System.Collections.ObjectModel;

public class Stuff
{
    public Stuff(string name)
    {
        this.Name = name;
    }

    public string Name { get; set; }
}


ObservableCollection<Stuff> myData = new ObservableCollection<Stuff>();


myData.Add(new Stuff("abcd"));

【讨论】:

  • 我将更改我的代码以使用 ObservableCollection 并且当我在我的应用程序中实际有用的部分工作时我会记住 INotifyPropertyChanged :) 假设我没有控制权源代码(在 dll 中),即:具有 List 的类 Stuff。如何告诉我的应用 FrameworkElement 的 DataContext 已更改?
  • @GuillaumeGrillonLabelle 如果您没有源代码或者他们没有实现回调函数/委托,这将非常困难。最好的,我能给你的是刷新列表(缓冲区)并添加/删除任何差异并更新 ObserableCollection。您可能想稍微了解一下 MVVM 模式,我在这里阅读了一个非常基本的示例:stackoverflow.com/questions/25613212/…
猜你喜欢
  • 2022-01-02
  • 1970-01-01
  • 1970-01-01
  • 2014-08-02
  • 2015-11-27
  • 1970-01-01
  • 1970-01-01
  • 2012-08-11
  • 2014-12-22
相关资源
最近更新 更多