Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# WPF反序列化数据索引集合_C#_Wpf_Serialization_Data Binding_Binding - Fatal编程技术网

C# WPF反序列化数据索引集合

C# WPF反序列化数据索引集合,c#,wpf,serialization,data-binding,binding,C#,Wpf,Serialization,Data Binding,Binding,我查找了一些与我的问题类似的问题,但我无法找出代码错误的原因。所以 我有一个WPF示例应用程序来演示我遇到的问题。在此应用程序中,有一个类项: [Serializable] class Item : ISerializable { public int ID { get; set; } public string Name { get; set; } public DateTime DateStamp { get; set; } public Item() {

我查找了一些与我的问题类似的问题,但我无法找出代码错误的原因。所以

我有一个WPF示例应用程序来演示我遇到的问题。在此应用程序中,有一个类项:

[Serializable]
class Item : ISerializable
{
    public int ID { get; set; }
    public string Name { get; set; }
    public DateTime DateStamp { get; set; }

    public Item() { }

    public Item(SerializationInfo info, StreamingContext context)
    {
        ID = (int)info.GetValue("ID", typeof(int));
        Name = (string)info.GetValue("Name", typeof(string));
        DateStamp = (DateTime)info.GetValue("DateStamp", typeof(DateTime));
    }

    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        info.AddValue("ID", ID);
        info.AddValue("Name", Name);
        info.AddValue("DateStamp", DateStamp);
    }
}
此外,还有另一个名为Model的类。看起来是这样的:

class Model : INotifyPropertyChanged
{
    private ObservableCollection<Item> itemsList;

    public ObservableCollection<Item> ItemsList
    {
        get { return itemsList; }
        set
        {
            if (itemsList != value)
            {
                itemsList = value;
                OnPropertyChanged("ItemsList");
            }
        }
    }

    public Model()
    {
        itemsList = new ObservableCollection<Item>();
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
}
类模型:INotifyPropertyChanged
{
私人可观察收集项目列表;
公共可观测收集项目列表
{
获取{return itemsList;}
设置
{
如果(itemsList!=值)
{
itemsList=值;
OnPropertyChanged(“项目列表”);
}
}
}
公共模型()
{
itemsList=新的ObservableCollection();
}
公共事件属性更改事件处理程序属性更改;
受保护的虚拟void OnPropertyChanged(字符串propertyName)
{
PropertyChangedEventHandler处理程序=PropertyChanged;
if(handler!=null)handler(这是新的PropertyChangedEventArgs(propertyName));
}
}
有一个主窗口,上面有一个列表框和3个按钮:

public partial class MainWindow : Window
{
    private Model model;
    private static int counter = 0;

    public MainWindow()
    {
        InitializeComponent();

        model = new Model();
        listBoxItems.ItemsSource = model.ItemsList;
    }

    private void AddMoreSampleItem(object sender, RoutedEventArgs e)
    {
        model.ItemsList.Add(new Item
                      {
                          ID = ++counter,
                          Name = "Sample " + counter,
                          DateStamp = DateTime.Now.Date
                      });
    }

    private void Button1_Click_Serialize(object sender, RoutedEventArgs e)
    {
        using (Stream stream = File.Open("D:\\sample.qwertyasdf", FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
        {
            IFormatter bf = new BinaryFormatter();
            bf.Serialize(stream, model.ItemsList);
            stream.Close();
        }
    }

    private void Button2_Click_Deserialize(object sender, RoutedEventArgs e)
    {
        using (Stream stream = File.Open("D:\\sample.qwertyasdf", FileMode.Open, FileAccess.Read, FileShare.None))
        {
            IFormatter bf = new BinaryFormatter();
            model.ItemsList = (ObservableCollection<Item>)bf.Deserialize(stream);
            stream.Close();
        }
    }
}
公共部分类主窗口:窗口
{
私有模型;
专用静态整数计数器=0;
公共主窗口()
{
初始化组件();
模型=新模型();
listBoxItems.ItemsSource=model.ItemsList;
}
私有void AddMoreSampleItem(对象发送方,RoutedEventArgs e)
{
model.ItemsList.Add(新项
{
ID=++计数器,
Name=“Sample”+计数器,
DateStamp=DateTime.Now.Date
});
}
私有无效按钮1\u单击\u序列化(对象发送方,路由目标)
{
使用(Stream-Stream=File.Open(“D:\\sample.qwertyasdf”,FileMode.OpenOrCreate,FileAccess.Write,FileShare.None))
{
IFormatter bf=新的二进制格式化程序();
序列化(流、模型、项目列表);
stream.Close();
}
}
私有无效按钮2\u单击\u反序列化(对象发送方、路由目标方)
{
使用(Stream-Stream=File.Open(“D:\\sample.qwertyasdf”,FileMode.Open,FileAccess.Read,FileShare.None))
{
IFormatter bf=新的二进制格式化程序();
model.ItemsList=(ObservableCollection)bf.反序列化(流);
stream.Close();
}
}
}
在窗口的构造函数中,我将listbox的ItemsSource属性设置为“model”对象的ItemsList属性: listBoxItems.ItemsSource=model.ItemsList

现在,正如我所想,由于ItemsList实现了INotyfyPropertyChanged,因此每当model.ItemsList属性更改其值时,它都应该引发属性更改事件,并且listbox应该自动跟随更改

但是,列表框的内容并没有改变,当我单击向列表中添加示例项的按钮时,它似乎不再做出反应

列表框:

<ListBox x:Name="listBoxItems" ItemsSource="{Binding UpdateSourceTrigger=PropertyChanged}" ItemTemplate="{StaticResource ListTemplate}" HorizontalAlignment="Left" Height="100" Margin="10,78,0,0" VerticalAlignment="Top" />


如果有人发现了失败的原因,请帮我解决,我已经被这个问题困扰了4天了。但是,数据绑定似乎没有中断,但我对此不确定。

如果您希望在数据绑定属性更改时更新UI,则需要在属性更改的项目上实现
INotifyPropertyChanged
接口。您的模型已经实现了它,但您的
类尚未实现。因此,如果更改了
item.Name
属性,则UI中不会有更新。

为什么要在XAML和code behind中设置
ItemsSource
两次?请从XAML中删除
ItemsSource
,然后查看结果。没有任何更改。顺便问一下,如果我从XAML中取出
ItemsSource
属性,我如何在代码中定义UpdateSource属性?我已经尝试过了,但仍然是错误的。我调试了反序列化过程,效果很好,可观察的集合变化平稳,但在UI上没有响应。。。您的数据类型需要能够实现
INotifyPropertyChanged
接口,并且您的集合需要是
ObservableCollection
类型,但是您不能序列化其中包含
ObservableCollection
的类,因为它的事件被标记为非序列化。肯特·布加特写了一篇关于这种情况的文章。当我需要序列化数据时,我使用单独的类,只需将
列表
替换为
ObservableCollection
集合。感谢您提供的信息!明亮的如果您将此作为回答评论,我接受它作为此问题的答案。:)