DeepCopy在ComboBox SelectionChanged的事件处理程序上失败

时间:2013-11-10 22:13:15

标签: c# .net event-handling

需要在ComboBox选择更改的事件处理程序中执行深层复制 DeepCopy失败 但完全相同的DeepCopy在ctor和Button Click中的事件处理程序中取得了成功 在两台机器上复制了这个 是否愿意更改处理程序或深层副本,但我非常需要它在ComboBox SelectionChanged的事件处理程序中

在代码

中查找失败
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.ComponentModel;

namespace DeepCopy
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private List<TestClass> testClassList = new List<TestClass>();
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = this;
            try
            {
                TestClass tca = new TestClass();
                tca.Prop1 = "Tcaa";
                TestClass tcb = DeepClone<TestClass>(tca);
                tca.Prop1 = "TcaNew1";
                System.Diagnostics.Debug.WriteLine(tca.Prop1);
                System.Diagnostics.Debug.WriteLine(tcb.Prop1);
                tcb.Prop1 = "sdf1";
                System.Diagnostics.Debug.WriteLine(tcb.Prop1);
            }
            catch (Exception Ex)
            {
                System.Diagnostics.Debug.WriteLine(Ex.Message);
            }
            TestClass tc = new TestClass();
            tc.Prop1 = "tc1";
            testClassList.Add(tc);
            tc = new TestClass();
            tc.Prop1 = "tc2";
            testClassList.Add(tc);
            foreach (TestClass tcx in TestClassList)
            {
                try
                {
                    // this does not fail
                    TestClass tcb = DeepClone<TestClass>(tcx);
                    System.Diagnostics.Debug.WriteLine(tc.Prop1);
                    System.Diagnostics.Debug.WriteLine(tcb.Prop1);
                    tc.Prop1 += "ctorA";
                    System.Diagnostics.Debug.WriteLine(tc.Prop1);
                    System.Diagnostics.Debug.WriteLine(tcb.Prop1);
                    tcb.Prop1 += "ctorB";
                    System.Diagnostics.Debug.WriteLine(tcb.Prop1);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                }
            }
        }
        public List<TestClass> TestClassList { get { return testClassList; } }
        [Serializable()]
        public abstract class TestAstract : INotifyPropertyChanged
        {
            public event PropertyChangedEventHandler PropertyChanged;
            protected void NotifyPropertyChanged(String info)
            {
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs(info));
                }
            }
            public abstract string Prop1 { get; set; }
        }
        [Serializable()]
        public class TestClass : TestAstract
        {            
            private string prop1;
            public override string Prop1 
            {
                get { return prop1; }
                set
                {
                    if (prop1 == value) return;
                    prop1 = value;
                    NotifyPropertyChanged("Prop1");
                }
            }
            public TestClass() { }
        }
        public static T DeepClone<T>(T obj)
        {
            using (var ms = new MemoryStream())
            {
                var formatter = new BinaryFormatter();
                formatter.Serialize(ms, obj);
                ms.Position = 0;

                return (T)formatter.Deserialize(ms);
            }
        }

        private void clickDeepCopy(object sender, RoutedEventArgs e)
        {
            foreach (TestClass tc in TestClassList)
            {
                try
                {
                    // this does not fail
                    TestClass tcb = DeepClone<TestClass>(tc);
                    System.Diagnostics.Debug.WriteLine(tc.Prop1);
                    System.Diagnostics.Debug.WriteLine(tcb.Prop1);
                    tc.Prop1 += "clickA";
                    System.Diagnostics.Debug.WriteLine(tc.Prop1);
                    System.Diagnostics.Debug.WriteLine(tcb.Prop1);
                    tcb.Prop1 += "clickB";
                    System.Diagnostics.Debug.WriteLine(tcb.Prop1);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                }
            }
        }

        private void cbSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            foreach (TestClass tc in TestClassList)
            {
                try
                {
                    // this fails
                    TestClass tcb = DeepClone<TestClass>(tc);
                    // A first chance exception of type 'System.Runtime.Serialization.SerializationException' occurred in mscorlib.dll
                    // Type 'System.ComponentModel.PropertyChangedEventManager' in Assembly 'WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' is not marked as serializable.
                    // A first chance exception of type 'System.Runtime.Serialization.SerializationException' occurred in mscorlib.dll
                    System.Diagnostics.Debug.WriteLine(tc.Prop1);
                    System.Diagnostics.Debug.WriteLine(tcb.Prop1);
                    tc.Prop1 += "cbceA";
                    System.Diagnostics.Debug.WriteLine(tc.Prop1);
                    System.Diagnostics.Debug.WriteLine(tcb.Prop1);
                    tcb.Prop1 = "cbceB";
                    System.Diagnostics.Debug.WriteLine(tcb.Prop1);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                }
            }
        }
    }
}

<Window x:Class="DeepCopy.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <Button Grid.Row="0" Content="DeepCopy" Click="clickDeepCopy" />
        <ComboBox Grid.Row="1" ItemsSource="{Binding Path=TestClassList}" DisplayMemberPath="Prop1" SelectionChanged="cbSelectionChanged" />
    </Grid>
</Window>

更有趣的是 尝试了一个空的ComboBox SelectionChanged事件处理程序
在调用空的ComboBox SelectionChanged后,按钮单击将失败

在XAML中删除了ComboBox SelectionChanged事件处理程序 在ComboBox SelectionChanged之后,按钮单击将失败 - 即使没有事件处理程序
但Button Click将在ComboBox SelectionChanged

之前成功

在XAML中删除了ComboBox SelectionChanged事件处理程序 在XAML中设置SelectedIndex = 0 Button Click事件处理程序将在第一次失败

即使没有SelectionChanged事件处理程序而且ComboBox上没有SelectedIndex,仍然会在TestClassList上调用get 单独的原始绑定不会破坏深层复制 在ComboBox上选择任何项目后,深层复制将中断

我知道你很怀疑,但我花了几个小时才知道这个

2 个答案:

答案 0 :(得分:3)

您需要在活动中添加[field:NonSerialized]

[field:NonSerialized]
public event PropertyChangedEventHandler PropertyChanged;

答案 1 :(得分:2)

您需要禁用PropertyChanged事件的序列化(即,由于数据绑定,ComboBox等订阅者)。

看看这个类似的问题How do I ignore event subscribers when serializing an object?