0

我有一个ObservbleCollection与列表框的绑定。将集合作为列表的 ItemsSource 后,我无法更新我的集合。如果我更新它,程序将关闭(没有任何崩溃)。

代码:
我有课程:

class MyFile
{
    String FileName {get; set;}
    ImageSource Ico {get; set;}
}

然后在构造器中运行代码(在 InitializeComponents 之后)

ObservableCollection<MyFile> filesList = new ObservableCollection<MyFile>();
filesList.Add(new MyFile { Name = "bar.doc", Ico = null } // Work Fine
filesList.Add(new MyFile { Name = "foo.txt", Ico = null } // Work Fine
files.ItemsSource = filesList; 
filesList.Add(new MyFile { Name = "try.txt", Ico = null } // EXIT FROM PROGRAM

我的程序有什么问题?

编辑
刚刚用 null 而不是 GetIcon 测试了它

4

2 回答 2

0

ObservableCollection的任务是向侦听器宣布更改(添加、删除、...)。所以没有任何问题,ObservableCollection并将其绑定为ItemsSourceListBox,不会使其不可编辑。该方法一定有问题GetIcon(例如,尝试重新打开未正确关闭的同一图像)

要看看这个想法是否正确,试试这个:

ObservableCollection<MyFile> filesList = new ObservableCollection<MyFile>();
filesList.Add(new MyFile { Name = "bar.doc", Ico = GetIcon(".doc") }
//filesList.Add(new MyFile { Name = "foo.txt", Ico = GetIcon(".txt") } // Comment this line
files.ItemsSource = filesList; 
filesList.Add(new MyFile { Name = "try.txt", Ico = GetIcon(".txt") } 

如果你想看到这个错误。我建议您在按钮的单击事件中(而不是在构造函数中)复制这些行,然后运行您的应用程序。

于 2013-03-31T13:28:58.783 回答
0

这是一个使用 DependencyPropery 绑定 ObservableCollection 的小示例。我希望它可以帮助您了解如何以这种方式进行 DataBinding。

XAML

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        x:Name="MyWindow"

        Title="MainWindow">
    <Grid>
        <ListBox ItemsSource="{Binding MyList, ElementName=MyWindow, Mode=TwoWay}">
        </ListBox>
    </Grid>
</Window>

代码背后

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;

using System.Collections.ObjectModel;

namespace WpfApplication1
{
    /// <summary>
    /// Logica di interazione per MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public static readonly DependencyProperty MyListProperty = DependencyProperty.Register("MyList", typeof(ObservableCollection<string>), typeof(MainWindow));

        public ObservableCollection<string> MyList
        {
            get
            {
                return (ObservableCollection<string>)GetValue(MyListProperty);
            }
            set
            {
                SetValue(MyListProperty, value);
            }
        }
        public MainWindow()
        {
            InitializeComponent();

            MyList = new ObservableCollection<string>() { "a", "b" };
            MyList.Add("c");
        }
    }
}
于 2013-03-31T14:25:06.890 回答