【问题标题】:Silverlight - XamlParseException The type 'Type' was not foundSilverlight - XamlParseException 找不到类型“类型”
【发布时间】:2015-03-13 17:34:14
【问题描述】:

找不到类型“类型”。 [行: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);

        }

【问题讨论】:

  • 在发生错误的情况下,您确定 Visual Tree 包含“telerik:GridViewCell”吗?
  • @JamesHarcourt 问题与此无关。错误消息明确指出 XAML 解析器找不到类型 Type(实际上是 x:Type,或 System.Windows.Markup.TypeExtension)。
  • 据我了解,就读者所知,在解析此 XAML 时基本上没有可视化树。
  • 我不太确定@HighCore - OP 明确指出,只有当他尝试将 TextBox 的 width 属性绑定到第一个 telerik:GridViewCell 的 ActualWidth 属性时,才会发生错误找到了视觉树。
  • @JamesHarcourt 看到我的回答。

标签: xaml silverlight xamlreader


【解决方案1】:

您有一个Silverlight 项目。 Silverlight 不支持标记扩展 x:Type。 Silverlight 中的祖先绑定如下所示:

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

[编辑] 顺便说一句,你不能绑定到ActualWidth。你必须观察SizeChanged 事件并有一些处理代码。你会发现这个问题的相当优雅的解决方案here: binding-to-actualwidth

【讨论】:

    【解决方案2】:

    该错误是由于 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);
    

    【讨论】:

    • 感谢您的回答。我刚刚意识到我指定了 WPF,实际上,它是一个 silverlight 项目。我将尝试查看您的链接是否也适用于我的场景。谢谢。暂时我会给你+1
    • 我刚刚检查过,似乎这个 ParserContext 使用 XamlReader.Parse(显然)而不是 Load。这是 Silverlight 中我唯一可用的东西。无论如何,至少你已经解释了问题发生的原因。
    猜你喜欢
    • 1970-01-01
    • 2017-11-09
    • 1970-01-01
    • 2014-01-25
    • 1970-01-01
    • 2018-08-28
    • 2019-05-09
    • 1970-01-01
    相关资源
    最近更新 更多