I created a UserControl. It contains several elements of specific style and have a DockPanel to contain children which added later on MainWindow.xaml. It works properly and can have it's children on MainWindow.xaml. But when you set Name property on the any of children, It produces 'the name is aleady used' exception on compiling. What do I have to think more about? Without setting Name property, it works properly.
Exception: Cannot set Name attribute value 'ThisProduceAnError' on element 'TextBlock'. 'TextBlock' is under the scope of element 'PropertyPanel', which already had a name registered when it was defined in another scope.
UserControl.xaml
<UserControl x:Class="TrainingWpf1.PropertyPanel"
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"
xmlns:local="clr-namespace:TrainingWpf1"
mc:Ignorable="d"
d:DesignHeight="120" d:DesignWidth="260">
<DockPanel>
<TextBlock DockPanel.Dock="Top" Text="Title"/>
<Border Padding="10" BorderThickness="1" CornerRadius="6" Background="CadetBlue">
<DockPanel x:Name="panContent" />
</Border>
</DockPanel>
</UserControl>
UserControl.xaml.cs
using System.Windows;
using System.Windows.Controls;
using System.Windows.Markup;
namespace TrainingWpf1
{
[ContentProperty(nameof(Children))]
public partial class PropertyPanel : UserControl
{
public PropertyPanel()
{
InitializeComponent();
this.Children = panContent.Children;
}
public UIElementCollection Children
{
get => (UIElementCollection)GetValue(ChildrenProperty.DependencyProperty);
private set => SetValue(ChildrenProperty, value);
}
public static readonly DependencyPropertyKey ChildrenProperty = DependencyProperty.RegisterReadOnly(
nameof(Children),
typeof(UIElementCollection),
typeof(PropertyPanel),
new PropertyMetadata());
}
}
MainWindow.xaml
<Window x:Class="TrainingWpf1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:TrainingWpf1"
mc:Ignorable="d"
Title="MainWindow" Height="400" Width="400">
<Grid>
<local:PropertyPanel>
<TextBlock Name="ThisProduceAnError" Text="Hello"/>
</local:PropertyPanel>
</Grid>
</Window>