【问题标题】:Deserialization binding problem with nested custom objects嵌套自定义对象的反序列化绑定问题
【发布时间】:2011-08-07 04:23:18
【问题描述】:

我有一个使用 MVVM 模式在 WPF 中创建的应用程序。在这个应用程序中,我有一个电子邮件对象的 ObservableCollection。我有一个主详细信息表单,它在列表框中显示集合,类属性“地址”、“EType”和“isPrimary”分别显示在文本框、组合框和复选框中。

组合框有一个列表的EmailTypes作为ItemsSource,并且选中的项目绑定到ViewModel中SelectedItem的Type属性。

一切都很好,很容易。但是,我想序列化 ObservableCollection 以用于撤消目的。这也可以,使用 ISerializableSurrogate(方法here)。除了一个例外:

组合框不会绑定到 SelectedItem.EType 属性,至少最初不会。而不是在选择电子邮件对象时显示类型的ComboBox,而是与预序列化版本的情况一样,ComboBox为空(未选择)。如果我在组合框中手动选择类型,它将起作用,并更新 Selected Emails 类型属性。我必须手动“重置”两个对象之间的绑定(?)。

地址(字符串)和复选框(布尔值)工作正常。并且反序列化的电子邮件对象确实具有来自反序列化调用的预期 EType 嵌套对象;我可以在检查本地时在调试器中看到它。就好像绑定没有将 EType 对象的反序列化版本识别为有效的 Etype 对象...

任何想法到底是什么地方分崩离析?我知道还有其他一些方法可以满足我的撤消要求,但我真的很想知道为什么这不起作用...

仅供参考,我知道这不是 ObservableCollection 的问题,因为我可以创建一个新的 ObservableCollection,手动添加原始电子邮件对象和反序列化的电子邮件对象,我也有同样的问题。

这是我的课程,非常简化:

这里是一个业务对象:

[Serializable]
public class Email : INotifyPropertyChanged
{
    private int _id;
    private string _address;
    private emailType _eType;
    private bool isPrimary;

    public string Address 
    {
        get { return _address; }
        set 
        { 
            _address = value;
            onPropertyChanged(new PropertyChangedEventArgs("Address"));
        }
    }
    public EmailType EType 
    {
        get { return _eType; }
        set 
        { 
            _type = value;
            onPropertyChanged(new PropertyChangedEventArgs("EType"));
        }
    }
    public bool IsPrimary 
    {
        get { return _isPrimary; }
        set 
        { 
            _isPrimary = value;
            onPropertyChanged(new PropertyChangedEventArgs("IsPrimary"));
        }
    }

这里有一个查找类:

[Serializable]
public class emailType
{
    protected readonly int _id;
    protected String _name;

    public int Id
    {
        get { return _id; }
    }
    public String Name
    {
        get { return _name; }
    }
}

XAML 中的组合框:

<ComboBox Grid.Column="1" Grid.Row="3" Height="23" HorizontalAlignment="Left" Margin="3" Name="typeComboBox" VerticalAlignment="Top" Width="190" 
              ItemsSource="{Binding EmailTypes}" IsSynchronizedWithCurrentItem="False"   >
        <ComboBox.SelectedItem>
            <Binding Path="SelectedEmail.EType"  NotifyOnValidationError="True" UpdateSourceTrigger="PropertyChanged">
                <Binding.ValidationRules>
                    <local:NullValueRule></local:NullValueRule>
                </Binding.ValidationRules>
            </Binding>
        </ComboBox.SelectedItem>

    </ComboBox>

【问题讨论】:

    标签: c# wpf xaml data-binding serialization


    【解决方案1】:

    您需要覆盖 emailType 类中的 Equals 方法。如果不这样做,则使用从对象继承的实现。

    此实现比较对象引用。反序列化的对象可能具有所有相同的属性,但它是不同的对象,并且不会“相等”。

    【讨论】:

    • 哇,我是不是觉得很害羞……我花了这么多时间寻找最复杂的答案……谢谢提醒!!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多