【问题标题】:Cannot serialize a generic type 'System.Windows.FreezableCollection`无法序列化泛型类型“System.Windows.FreezableCollection”
【发布时间】:2012-07-18 09:55:49
【问题描述】:

希望是一个简单的问题。我有一个自定义控件,其依赖属性包含另一个自定义控件的列表。

public static readonly DependencyProperty BlockObjectsProperty = DependencyProperty.Register("BlockObjects", typeof(FreezableCollection<BlockObject>), typeof(Block), new FrameworkPropertyMetadata(new FreezableCollection<BlockObject>(), null));
public FreezableCollection<BlockObject> BlockObjects
{
     get { return (FreezableCollection<BlockObject>)base.GetValue(BlockObjectsProperty); }
     set { base.SetValue(BlockObjectsProperty, value); }
}

然后在 xaml 中使用它来填充控件

<Viewbox Grid.Row="2" Stretch="Uniform">
    <ItemsControl x:Name="tStack" ItemsSource="{TemplateBinding BlockObjects}" ContextMenu="{StaticResource BodyContextMenuKey}">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <StackPanel Orientation="Vertical"  VerticalAlignment="Stretch" />
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
     </ItemsControl>
</Viewbox>

我现在的问题是我想将它序列化到一个文件中,但是在使用 XamlWriter.Save 时我得到“无法序列化泛型类型“System.Windows.FreezableCollection”。如果这是一个普通的类,我可以使用属性来描述它应该被序列化的方式(对吗?)但它是一个静态依赖属性,那么我如何让它序列化呢?

【问题讨论】:

    标签: wpf xaml serialization


    【解决方案1】:

    好吧,愚蠢的我,网上有很多关于这方面的信息,简单的解决方案是采用泛型 freezablecollection 并派生一个非泛型类,如下所示。

    public class BlockObjectCollection : FreezableCollection<BlockObject>
    {
    }
    

    然后替换依赖属性

        public static readonly DependencyProperty BlockObjectsProperty = DependencyProperty.Register("BlockObjects", typeof(BlockObjectCollection), typeof(Block), new FrameworkPropertyMetadata(new BlockObjectCollection(), null));
        public BlockObjectCollection BlockObjects
        {
            get { return (BlockObjectCollection)base.GetValue(BlockObjectsProperty); }
            set { base.SetValue(BlockObjectsProperty, value); }
        }
    

    【讨论】:

    • 难以置信但真实!这也适用于 ObservableCollection
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-29
    • 1970-01-01
    • 1970-01-01
    • 2014-09-23
    • 1970-01-01
    • 1970-01-01
    • 2018-04-27
    相关资源
    最近更新 更多