如何在设置数据绑定后向ListBox添加项目?

3

我可以帮您翻译成中文。这段内容涉及到IT技术,是关于创建Windows Phone 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>

好的,这很有效,当我启动应用程序时,我可以看到列表及其四个项目。

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有什么区别?
谷歌并没有提供太多帮助,我找到的东西可能是针对旧版本的Windows Phone或普通的WPF或ASP.Net的...
还有一件奇怪的事情发生了,在将项目添加到列表后,什么也没发生,当我点击旧项目时,会出现灾难性的错误。我还没有在我的列表项上绑定事件。
我快要放弃数据绑定了,只是按照代码逐步构建应用程序。向列表中添加东西不应该那么难,我做错了什么?

3
使用ObservableCollection<T>代替List<T>。 - Vlad
1个回答

0

需要使用 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<T>,并在我处理实际有用的应用程序部分时记得使用INotifyPropertyChanged :)假设我没有控制源代码(在dll中),即类Stuff具有List<OtherStuff>。 我如何告诉我的应用程序DataContext已更改的FrameworkElement? - Guillaume Grillon Labelle
如果您没有源代码或者他们没有实现回调函数/委托,那么这将非常困难。最好的方法是刷新列表(缓冲区),添加/删除任何差异并更新ObserableCollection。您可能需要稍微了解一下MVVM模式,我有一个非常基本的例子在这里:https://dev59.com/Q4Pba4cB1Zd3GeqPmQK_#25627927 - Chubosaurus Software

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接