2012-07-18 96 views
1

希望有一个简单的问题。我有一个包含另一个自定义控件列表的依赖项属性的自定义控件。无法序列化泛型类型'System.Windows.FreezableCollection`

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> 

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

回答

5

好傻傻的我有很多关于这个网络的信息,简单的解决方案是采用通用的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); } 
    } 
+0

难以置信,但却是事实!这对ObservableCollection <>也是有效的 – Ozzy 2017-05-30 21:19:25

相关问题