Silverlight - XamlParseException类型'类型'没找到

时间:2015-03-13 17:34:15

标签: xaml silverlight xamlreader

  

类型'类型'没找到。 [行:7位置:21]

我试图动态生成数据模板。它工作正常,但如果我包含此属性,我会得到上述异常。

Width="{Binding Path=ActualWidth,RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type telerik:GridViewCell}}}"

完整的方法:

  public DataTemplate GetTextColumnTemplate(int index)
        {

            string templateValue = @"
            <DataTemplate 
            xmlns:sys=""clr-namespace:System;assembly=mscorlib""  
            xmlns:telerik=""http://schemas.telerik.com/2008/xaml/presentation"" 
            xmlns=""http://schemas.microsoft.com/client/2007""
            xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml"">
                <StackPanel>
                    <TextBox Width=""{Binding Path=ActualWidth,RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type telerik:GridViewCell}}}"" Text=""{Binding Path=V" + (index + 1).ToString() + @",Mode=TwoWay}"" AcceptsTab=""True"" AcceptsReturn=""True""/>
                </StackPanel>
            </DataTemplate>";


            return (DataTemplate)XamlReader.Load(templateValue);

        }

2 个答案:

答案 0 :(得分:1)

导致错误是因为XAML解析器无法将XAML中的类型x:Type解析为有效的CLR类型,可能是因为XAML读取器中的命名空间映射在没有适当的上下文的情况下无法由XAML读取器正确处理。

我有this的自定义版本,它使用ParserContext来定义XAML的XML命名空间映射:

var context = new ParserContext {XamlTypeMapper = new XamlTypeMapper(new string[0])};

context.XmlnsDictionary.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation");
context.XmlnsDictionary.Add("x", "http://schemas.microsoft.com/winfx/2006/xaml");
//... And so on add other xmlns mappings here.

var template = (DataTemplate) XamlReader.Parse(yourXAMLstring, context);

答案 1 :(得分:1)

您有一个Silverlight项目。 Silverlight不支持标记扩展x:Type。 Silverlight中的祖先绑定看起来像这样:

{Binding Path=Foo, RelativeSource={RelativeSource AncestorType=UserControl}}

[编辑] 顺便说一句,你无法绑定ActualWidth。您必须观察SizeChanged事件并获得一些处理代码。你会发现这个问题非常优雅的解决方案here: binding-to-actualwidth