绑定后的ObservableCollection更新

时间:2013-03-31 13:15:40

标签: c# wpf observablecollection

我有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

2 个答案:

答案 0 :(得分:0)

ObservableCollection的任务是向听众宣布更改(添加,删除......)。因此ObservableCollection没有任何问题,并将其绑定为ListBox的ItemsSource,不会使其无法编辑。 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") } 

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

答案 1 :(得分: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");
        }
    }
}