无法序列化泛型类型“System.Windows.FreezableCollection" [英] Cannot serialize a generic type 'System.Windows.FreezableCollection`

查看:40
本文介绍了无法序列化泛型类型“System.Windows.FreezableCollection"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Hopefully a simple question. I have a custom control with a dependency property that contains a list of another custom control.

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 中使用它来填充控件

this is then used within xaml to populate the controls

<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’".如果这是一个普通类,我可以使用属性来描述它应该被序列化的方式(对吗?)但它是一个静态依赖属性,那么我如何让它序列化?

My problem now is i want to serialize this out to a file but i'm getting 'Cannot serialize a generic type 'System.Windows.FreezableCollection`' when using XamlWriter.Save. if this was a normal class i could use attributes to describe the way it should be serialized (right?) but its a static dependency property so how do i get this to serialize?

推荐答案

好吧,我傻了,网上有很多关于这个的信息,简单的解决方案是采用通用的 freezablecollection 并派生一个非通用的类,如下所示.

Ok Silly me there is alot of information about this all over the net, the simple solution is to take the generic freezablecollection and derive a none generic class as below.

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); }
    }

这篇关于无法序列化泛型类型“System.Windows.FreezableCollection"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆