【发布时间】:2020-06-27 16:12:24
【问题描述】:
我创建了一个 UserControl。它包含几个特定样式的元素,并有一个 DockPanel 来包含稍后在 MainWindow.xaml 上添加的子项。 它可以正常工作,并且可以在 MainWindow.xaml 上拥有它的子级。但是,当您在任何子项上设置 Name 属性时,它会在编译时产生“名称已被使用”异常。 我还需要考虑什么?不设置 Name 属性,它可以正常工作。
异常:无法在元素“TextBlock”上设置名称属性值“ThisProduceAnError”。 “TextBlock”在元素“PropertyPanel”的范围内,当它在另一个范围内定义时,它已经注册了一个名称。
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>
【问题讨论】:
-
能否请您添加整个异常?
-
我在帖子中添加了整个异常。
-
在我的原始代码中,它还有其他东西,如折叠按钮、事件、处理程序等。我不知道如何只用 ContentControl 和它的样式模板来处理这些东西。