Toggle Column Visibility Change with Text Block in Header results in error

Dec 15, 2009 at 6:33 PM

I create a column dynamically with the following code:


DataGridTextColumn col = new DataGridTextColumn();
TextBlock text = new TextBlock(new Run("Header"));
col.Header = text;
//col.Header = "Header";

When I toggle visibility from Visible to Hidden and backwards I receive the following error: "Specified element is already the logical child of another element. Disconnect it first.".

All is well when using just a text instead of a TextBlock (the commented line).


Am I doing something wrong here or is this a bug?


Dec 30, 2009 at 2:21 PM

I am having the same problem. Have you found a workaround yet for this problem?

Thanks in advance

Dec 30, 2009 at 2:42 PM

The same problem arises when you create many columns in code btw.

Yep I used a different approach (which works here) using headerbinding.

The code:

Style headerStyle = (Style)Resources["ColumnHeaderStyle"];
DataGridTextColumn col = new DataGridTextColumn();
myColumnInfo colInfo = new myColumnInfo(...);
col.HeaderStyle = headerStyle;
col.Header = colInfo;
Binding visiblityBinding = new Binding("ColVisibility");
visiblityBinding.Source = colInfo;
BindingOperations.SetBinding(col, DataGridTextColumn.VisibilityProperty, visiblityBinding);

The Class:

    public class myColumnInfo : INotifyPropertyChanged
        public string Name { get; set; }
        private Visibility colVisibility;
        public myColumnInfo()
            : base()
            // for serialisation
        public myColumnInfo(...)
            Name = name;
            colVisibility = Visibility.Visible;
        public Visibility ColVisibility
            get { return colVisibility; }
                if (colVisibility != value)
                    colVisibility = value;
        [field: NonSerialized]
        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged(string propertyName)
            if (PropertyChanged != null)
                  new PropertyChangedEventArgs(propertyName));

And the xaml:

<Style x:Key="ColumnHeaderStyle" TargetType="dg:DataGridColumnHeader">
                <Setter Property="ContentTemplate">
                                <TextBlock Text="{Binding Name}" HorizontalAlignment="Center" VerticalAlignment="Center" />



Dec 31, 2009 at 12:26 AM

Hi All,

Is it similar to this problem?

Dec 31, 2009 at 7:25 AM

It looks the same.

I do have EnableColumnVirtualization=true in my code.