【问题标题】:How can i serialize a WPF custom control which has a property of type ObservableCollection?如何序列化具有 ObservableCollection 类型属性的 WPF 自定义控件?
【发布时间】:2016-09-13 08:10:24
【问题描述】:

我正在编写一个 WPF 窗口设计器应用程序。 在设计器中,我可以将自定义控件添加到窗口并通过将添加的自定义控件所在的画布面板序列化到 XAML 来保存窗口。

public string SerializeControlToXaml(FrameworkElement control)
{
    StringBuilder outstr = new StringBuilder();

    XmlWriterSettings settings = new XmlWriterSettings();
    settings.Indent = true;
    settings.OmitXmlDeclaration = true;
    XamlDesignerSerializationManager dsm =
            new XamlDesignerSerializationManager(XmlWriter.Create(outstr, settings));
    dsm.XamlWriterMode = XamlWriterMode.Expression;
    System.Windows.Markup.XamlWriter.Save(control, dsm);

    string xaml = outstr.ToString();
    return xaml;
}

在序列化之后,我将 xaml 作为字符串并将其保存在一个文件中,以便稍后重新加载。

现在我的问题是我向我的一个自定义控件添加了一个新的依赖属性,该控件的类型为 ObservableCollection。 每次我设置该属性并尝试将画布序列化为 XAML 时,我都会收到一条错误消息:

“'ObservableCollection 1'. The sign '' 中的首字母无效,十六进制值 0x60,可能不包含在名称中。”

我从不给这个系列起名字。 怎么了?

这是我绑定控件的视图模型属性:

public ObservableCollection<string> SelectedFormulas
{
    get
    {
        return selectedFormulas;
    }
    set
    {
        selectedFormulas = value;
        RaisePropertyChanged("SelectedFormulas");
    }
}

这是我的依赖属性:

public static readonly DependencyProperty SelectedFormulasProperty =
        DependencyProperty.Register("SelectedFormulas", typeof(ObservableCollection<string>), typeof(CustomNumericField));

public ObservableCollection<string> SelectedFormulas
{
    get { return GetValue(SelectedFormulasProperty) as ObservableCollection<string>; }
    set { SetValue(SelectedFormulasProperty, value); }
}

【问题讨论】:

  • 检查控件的x:Name 或Name 以确保它不包含撇号(')。
  • 它可能会窒息通用。使您的属性返回一个子类:public class StringObservableCollection : ObservableCollection&lt;string&gt;.
  • 是的,它是通用的。创建集合的非泛型子类,如Cannot serialize a generic type 'System.Windows.FreezableCollection` 的答案所示。
  • 您不应明确使用ObservableCollection&lt;T&gt; 作为属性类型。最好使用基本集合类型并在运行时检查它是否实现了INotifyCollectionChanged,如下所述:stackoverflow.com/a/9128855/1136211
  • 非常感谢 dbc!这有帮助。

标签: c# wpf xaml serialization


【解决方案1】:

dbc 给出的答案就是解决方案。

我需要的是一个非泛型类而不是 ObservableCollection。

这是新课程:

public class SelectedFormulaCollection : ObservableCollection<string>
{
}

这里是自定义控件中的 DependencyProperty(视图模型中的属性类型也必须更改!):

    public static readonly DependencyProperty SelectedFormulasProperty =
        DependencyProperty.Register("SelectedFormulas", typeof(SelectedFormulaCollection), typeof(CustomNumericField));

    public SelectedFormulaCollection SelectedFormulas
    {
        get { return GetValue(SelectedFormulasProperty) as SelectedFormulaCollection; }
        set { SetValue(SelectedFormulasProperty, value); }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-19
    • 1970-01-01
    • 1970-01-01
    • 2012-02-12
    相关资源
    最近更新 更多