How to add UserControl to a Panel on a WPF Window

I think I'm missing something that should be obvious here, but I'm drawing a blank on this one.

I've built a very primitive UserControl containing nothing more than a TextBox to use as a log window:

<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>

I don't expect that to be the best way to do it, but it should be good enough for a prototype.

The code-behind is similarly simple:

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
}

The thing I can't figure out is how to add this control to my MainWindow.xaml . Simplifying, lets say my window looks like this:

<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>

Even with something so simple, the Designer in Visual Studio 2010 can't load the main window. The error given is:

A value of type 'LoggerControl' cannot be added to a collectionor dictionary of type 'UIElementCollection'.

This error message has only one unrelated hit in the major search engines (plus duplicates) so I haven't found any useful help. Microsoft's own documentation seems to imply that this should work.

Any idea how to solve this?


<UserControl x:Class="My.LoggerControl"


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

Looks like you may have made a mistake in the namespacing? LoggerControl is listed as being the namespace My, while you're importing My.LogTest and assigning it to the xml-prefix local. Change this to:

xmlns:local="clr-namespace:My"

And I think it should work. Otherwise, fix the LoggerControl declaration.

链接地址: http://www.djcxy.com/p/10934.html

上一篇: Android以编程方式将平铺图像作为背景

下一篇: 如何将UserControl添加到WPF窗口上的Panel