【问题标题】:Exception while XamlReader.Load(..)XamlReader.Load(..) 时出现异常
【发布时间】:2014-04-02 16:29:56
【问题描述】:

我在 (UIElement)XamlReader.Load(...) 期间收到一个异常,上面写着

'Cannot create unknown type 'TextBox'.' Line number '1' and line position '2'.

在以下 xaml 上:

<TextBox Name="inputMyFirstString" BorderThickness="0" HorizontalAlignment="Stretch" Text="test"></TextBox>

我做错了什么?

【问题讨论】:

    标签: c# xaml


    【解决方案1】:

    我知道这是一个老问题,但我认为仍然缺少“正确”的答案。 您可以通过在代码中添加所需的命名空间来避免更改 XAML:

    ParserContext context = new ParserContext();
    context.XmlnsDictionary.Add("","http://schemas.microsoft.com/winfx/2006/xaml/presentation");
    context.XmlnsDictionary.Add("x", "http://schemas.microsoft.com/winfx/2006/xaml");
    //etc.
    
    object content = XamlReader.Load(stream, context);
    

    【讨论】:

      【解决方案2】:

      我认为,这是由于missing namespace。试试

      <TextBox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" ...
      

      【讨论】:

      • 这会起作用,但是将命名空间添加到 XAML 中的每个控件并不是一个好主意。最好在全局范围内定义它。
      • @Winston Smith:我已经在我的控件中定义了命名空间,并添加了文本框。我还能在哪里全局定义命名空间?
      【解决方案3】:

      将 xmlns 属性添加到 XAML 中的 Window 元素:

      <Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" ...
      

      【讨论】:

        猜你喜欢
        • 2013-03-08
        • 2014-09-25
        • 2011-12-23
        • 1970-01-01
        • 1970-01-01
        • 2021-03-31
        • 2018-01-31
        • 2011-10-15
        • 2021-08-05
        相关资源
        最近更新 更多