I was looking at an answer on how to set the visibility of a data grid column, so i added
<UserControl.Resources>
<BooleanToVisibilityConverter x:Key="b2v" />
</UserControl.Resources>
and then in my xaml I have
<DataGridTemplateColumn Visibility="{Binding Source={x:Reference ShowLookupCheckbox},
Path=IsChecked
Converter={StaticResource b2v}}" >
...
</DataGridTemplateColumn>
When my app starts and the checkbox is clear the column is correctly collapsed. When I check the checkbox the column correctly shows. When I click on the checkbox again the column agains is correctly collapsed. However, when I click to enable the checkbox a second time I get an InvalidOperationException
"Specified element is already the logical child of another element. Disconnect it first."
I tried changing the Mode to one way but that didn't help. Anyone know what I'm doing wrong or how to interpret this exception?
I don't think the content of the column matters as it works correctly without the Visibility setting but for the sake of completion here's the full xaml I elided with ... above
<DataGridTemplateColumn.Header>
<TextBlock Style="{StaticResource DataGridHeader}">MO Lookup</TextBlock>
</DataGridTemplateColumn.Header>
<DataGridTemplateColumn.CellTemplate >
<DataTemplate >
<Hots:AutoCompleteBoxEx ToolTip="Start typing a Master Order Id"
ItemsSource="{Binding AllMoLines,
UpdateSourceTrigger=PropertyChanged}"
Width="50"
HorizontalContentAlignment="Left"
FilterMode="StartsWith"
IsDropDownOpen="True"
IsTextCompletionEnabled="True"
LostFocus="MoLineBoxLostFocus"
SelectedItem="{Binding Path=SelectedMoLine, Mode=TwoWay}" >
<Hots:AutoCompleteBoxEx.ItemTemplate>
<DataTemplate>
<Grid Width="500">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="50" />
<ColumnDefinition Width="400" />
<ColumnDefinition Width="50" />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding HssId, Mode=OneWay}"
Grid.Column="0" />
<TextBlock Text="{Binding Description, Mode=OneWay}"
Grid.Column="1" />
<TextBlock Text="{Binding Unit, Mode=OneWay}"
Grid.Column="2" />
</Grid>
</DataTemplate>
</Hots:AutoCompleteBoxEx.ItemTemplate>
</Hots:AutoCompleteBoxEx>
</DataTemplate>
[EDIT] Here are the first few lines from the Exception stack trace. The whole thing is 66 lines. It's the AddLogicalChild and ChangeLogicalParent that I find perplexing. I'm not sure why checking/unchecking a checkbox linked to a Visibility property is causing a child element to be added
System.InvalidOperationException was unhandled
Message=Specified element is already the logical child of another element. Disconnect it first.
Source=PresentationFramework
StackTrace:
at System.Windows.FrameworkElement.ChangeLogicalParent(DependencyObject newParent)
at System.Windows.FrameworkElement.AddLogicalChild(Object child)
at System.Windows.Controls.ContentControl.OnContentChanged(Object oldContent, Object newContent)