How to add UserControl to a panel in a WPF window

I think I am missing something that should be obvious here, but I draw a space on this.

I created a very primitive UserControl containing nothing more than a TextBox for 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 do not expect this to be the best way to do this, but it should be good enough for a prototype.

Code lag 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 } 

I cannot figure out how to add this control to my MainWindow.xaml . Simplification, 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, Designer in Visual Studio 2010 cannot load the main window. Indicated error:

A value of type "LoggerControl" cannot be added to the collector dictionary of type "UIElementCollection".

This error message contains only one unrelated hit in the major search engines (plus duplicates), so I did not find any useful help. Microsoft's documentation seems to imply that this should work.

Any idea how to solve this?

+7
source share
1 answer
 <UserControl x:Class="My.LoggerControl" xmlns:local="clr-namespace:My.LogTest" 

Looks like you made a mistake in the namespace? LoggerControl is listed as a My namespace, while you import My.LogTest and assign it to the local xml prefix. Change this to:

 xmlns:local="clr-namespace:My" 

And I think this should work. Otherwise, correct the LoggerControl declaration.

+3
source

All Articles