Cannot serialize a generic type 'System.Windows.FreezableCollection`

[亡魂溺海] 提交于 2020-01-11 11:17:07

问题


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

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>

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?


回答1:


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>
{
}

then replace the dependency properties

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


来源:https://stackoverflow.com/questions/11538761/cannot-serialize-a-generic-type-system-windows-freezablecollection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!