【发布时间】:2012-08-23 12:25:01
【问题描述】:
在将一堆 Frame 控件转换为更简单的 ContentControl 控件以在其逻辑父模型视图中托管子模型视图后,我最近开始收到异常“Specified element is already the logical child of another element. Disconnect it first."”。
在下面的示例中,注释掉的代码将阻止崩溃的发生:
<UserControl x:Class="GUI.Views.Scenario.PathogenRiskLiquidIngestionView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ScenModels="clr-namespace:GUI.ViewModels.ScenarioModels">
<StackPanel Orientation="Vertical">
<StackPanel Orientation="Vertical">
<DockPanel>
<Label DockPanel.Dock="Left" Content="Risk Assessment Title"></Label>
<TextBox DockPanel.Dock="Right" Text="{Binding RiskAssessmentTitle, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}"></TextBox>
</DockPanel>
<DockPanel>
<Label DockPanel.Dock="Left" Content="Risk Calculated"></Label>
<ComboBox SelectedItem="{Binding RiskCalculated, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}" ItemsSource="{Binding RiskCalculatedOptions}"></ComboBox>
</DockPanel>
<DockPanel>
<Label DockPanel.Dock="Left" Content="{Binding MinAcceptableInfectionRiskLabel}"></Label>
<TextBox DockPanel.Dock="Right" Text="{Binding MinAcceptableInfectionRisk, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}"></TextBox>
</DockPanel>
</StackPanel>
<!--<GroupBox Header="Pathogens">
<StackPanel Orientation="Vertical">
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
<Button Content="Add Pathogen" Command="{Binding AddPathogen}"></Button>
<Button Content="Remove Pathogen" Command="{Binding RemovePathogen}" CommandParameter="{Binding SelectedIndex, ElementName=PathogenList}"></Button>
</StackPanel>
<ListView Name="PathogenList" ItemsSource="{Binding PathogensPresentViews}" Tag="{Binding}" BorderThickness="0" Background="Transparent">
<ListView.ItemTemplate>
<DataTemplate DataType="{x:Type ScenModels:PathogenPresentIngestViewModel}">
<ContentControl Content="{Binding}"></ContentControl>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackPanel>
</GroupBox>
<GroupBox Header="Receptor Characteristics">
<StackPanel Orientation="Vertical">
<ContentControl Content="{Binding ReceptorVolumeLiquidIngestedPerEventView}"></ContentControl>
<ContentControl Content="{Binding ExposuresView}"></ContentControl>
</StackPanel>
</GroupBox>-->
</StackPanel>
</UserControl>
在搜索这种异常后,最常见的原因似乎是一些不正确的样式,但是在这个应用程序中,我还没有为任何元素设置样式。有人可以告诉我可能导致此异常的原因吗?
谢谢, 亚历克斯。
【问题讨论】:
-
另外值得一提的是,这似乎是导致此错误的唯一视图,并且在其他不会导致此错误的视图中有非常相似的 XAML。
-
说真的,这个错误很容易理解,如果一个常见的原因是样式无关紧要,你可以很容易地推断出是什么原因导致的,并查看相关的代码部分。
-
当元素已经作为子元素添加到某处时会发生异常,因此关键位置是:引用 UI 元素的位置以及以编程方式从树中添加和删除 UI 元素的位置。像
{Binding ExposuresView}这样的东西只会叫树冲突,你甚至不应该在数据中引用视图。我不能告诉你问题到底出在哪里(你应该是追踪它的人)。 -
我很抱歉,但我不认为它像你所说的那么简单,无论如何我看不到这些观点中的一个最终成为多个元素的逻辑子元素,这就是为什么我有难以追踪。
-
好吧,尽管如此,你还是设法做到了这一点,如果你有适当的模型视图分离,你就不会陷入困境......