【问题标题】:Relization of XElement, XAttribute + IDataErrorInfo for binding in wpf appwpf app中绑定XElement、XAttribute + IDataErrorInfo的实现
【发布时间】:2015-12-11 15:50:23
【问题描述】:

我在 wpf 应用程序中使用 mvvm 模式。作为数据源,我有 XDocument。在 UI 中,我将控件绑定到此 XDocument 中的 XElements 和 XAttribute 的值。 前任

<TextBox Text={Binding XElement[TitleNode].XElement[Title].Value} />

它允许我只将数据放在 XDoc 中,并允许避免从自定义模型到 xml 的数据转换。

现在我需要用 IDataErrorInfo 扩展模型的功能来实现错误通知。所以我需要向 XElement 和 XAttribute .net 类添加接口。 我有两个决定: 1) xelement 和 xattribute 的模式适配器,它将具有接口 IDataErrorInfo 的实现以及 xelement\xattribute 值的 Value setter\getter。弱点 - 我需要为所有 UI 输入控件创建适配器对象并绑定到它。 2) 创建子类,继承XElement\XAttribute,实现接口。 Weekness - 我需要将所有 xelements 和 xattributes 转换为我的子类。 哪种方式更好?

【问题讨论】:

  • 将您的 xml 反序列化为实现接口的类。这是最简单的方法。在小型原型中尝试一下。
  • 在你的情况下,如果我有困难的 xml 结构(至少 15 级),我将不得不定义许多用于反序列化的类,绑定到对象而不是 xdoc 并拥有许多数据源z
  • 嗯,然后创建一个对象图并自己进行翻译。

标签: mvvm binding xelement idataerrorinfo xattribute


【解决方案1】:

我猜最好的方法是继承 XElement/XAttribute 并添加你需要的接口。 我创建了 2 个子类 XElementCustom 和 XAttributeCustom。在构造函数中,整个树被递归地重新创建 这就是我的认识:

    /// <summary>
    /// Наследник XML с реализацией INotifyPropertyChanged
    /// </summary>
    public class XElementCustom : XElement, INotifyPropertyChanged, IDataErrorInfo, IDataErrorInfoValidating
    {
public XElementCustom(XElement sourceElement)
            :base(sourceElement.Name.LocalName)
        {

            if (sourceElement.Elements().Any())
            {
                foreach (var element in sourceElement.Elements())
                {
                    this.Add(new XElementCustom(element));
                }
            }
            else
            {
                this.Value = sourceElement.Value;
            }

            foreach (var attribute in sourceElement.Attributes())
            {
                this.Add(new XAttributeCustom(attribute));
            }

            _changedProperties = new List<string>();
        }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-16
    • 2011-06-27
    • 1970-01-01
    • 2015-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多