如何将UserControl添加到WPF窗口上的面板中

7
我觉得这里应该有一些显而易见的东西我没有想到,但是我对此一无所知。
我已经构建了一个非常原始的UserControl,里面只包含一个TextBox作为日志窗口:
<UserControl x:Class="My.LoggerControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             x:Name="LoggerView">
    <Grid x:Name="LayoutRoot">
        <TextBox x:Name="LogWindow" AcceptsReturn="True"/>
    </Grid>
</UserControl>

我不指望这是最佳的做法,但对于原型来说应该足够好了。
后台代码同样简单:
public partial class LoggerControl : UserControl, ILogger
{
    public LoggerControl()
    {
        InitializeComponent();
    }

    private LogLevel level = LogLevel.Warning;

    #region ILogger

    public LogLevel Level
    {
        get { return level; }
        set { level = value; }
    }

    public void OnError(string s)
    {
        if (level >= LogLevel.Error)
            LogWindow.AppendText("ERROR:::" + s + "\n");
    }

    // ...
    #endregion
}

我无法弄清楚如何将此控件添加到我的 MainWindow.xaml 中。简单来说,假设我的窗口长这样:
<Window x:Class="My.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:My"
    Title="Test" Height="350" Width="525">
    <Grid>
        <local:LoggerControl x:Name="LogView" />
    </Grid>
</Window>

即使是这么简单的事情,Visual Studio 2010 中的设计师也无法加载主窗口。给出的错误是:

无法将“LoggerControl”类型的值添加到“UIElementCollection”类型的集合或字典中。

这个错误信息在主要搜索引擎中只有一个无关的命中(加上重复的结果),所以我没有找到任何有用的帮助。微软自己的文档似乎暗示着这应该可以工作。
你有什么解决办法吗?

很奇怪,当我构建一个最小的测试应用程序时,我就没有这个问题。这是什么原因呢? - Ian Gilham
1个回答

3
<UserControl x:Class="My.LoggerControl"


 xmlns:local="clr-namespace:My.LogTest"

看起来你可能在命名空间方面犯了错误。LoggerControl被列为命名空间My,而你正在导入My.LogTest并将其分配给xml-prefix本地变量。请更改为:

xmlns:local="clr-namespace:My"

我认为它应该可以工作。否则,请修复LoggerControl声明。


很好,你发现了。不过那是我复制代码时疏忽了,把对我的雇主的引用给删掉了。我使用的命名空间是正确的。 - Ian Gilham

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接