0
votes

I need to hide a TextBlock that is child of a Border and is added to a Grid. The following code dynamically add the Border and the TextBlock to the Grid. Then if the Grid contain more than 5 children it hide the firsts children. It work correctly to hide the border but the TextBlock (the child of Border) remain visible.

Any idea where could be the problem? Thanks!

Border TextBorder = new Border();
TextBorder.BorderBrush = new SolidColorBrush(_settings.TextColor);
TextBorder.BorderThickness = new Thickness(0,0,0,2);
TextBorder.Padding = new Thickness(0, 10, 0, 10);
RowDefinition rd = new RowDefinition();
rd.Height = GridLength.Auto;
myGrid.RowDefinitions.Add(rd);
TextBlock uc = new TextBlock();
uc.Text = "Test";
TextBorder.Child = uc;
Grid.SetRow(TextBorder, myGrid.RowDefinitions.Count -1);
myGrid.Children.Add(TextBorder);

if (myGrid.Children.Count > 5)
{
    Border border = (Border)myGrid.Children[myGrid.Children.Count - 6];
    border.Visibility = Visibility.Hidden;
    border.Child.Visibility = Visibility.Hidden;
}

Update

The code work correctly. The problem was in OnRender event of the TextBlock that draw the text with some graphic effect. I though that if the control is invisible OnRender should not be raised but it seams that it is raised also when the control is invisible. I have not found a way to prevent OnRender to be raised, nor ClipToBound nor Invisible work. So I give up with this approach and I just check in OnRender if the TextBlock is in the visible area of the container.

1
Not really a clarification request, but anyway: why using code in WPF? Why not XAML? - dymanoid
border.Child.Visibility = Visibility.Hidden; why not use uc.Visibility = Visibility.Hidden; - Denis Schaf
@dymanoid I'v not understood your question. This code is in c# for a WPF application. I need to do this dynamically so I can't do it in the XAML code. - user2272143
@DenisSchaf Because I need to hide the firsts TextBlocks not the current added - user2272143
You can do everything dynamically in XAML, just use the styling and the templating mechanisms. But this is indeed off-topic for your question. - dymanoid

1 Answers

-1
votes

first of all, I think what you do is something you should not do! But here is how you can do it (btw this assumes you only add Borders to your grid):

if (myGrid.Children.Count > 5)
{
   (myGrid.Children[myGrid.Children.Count - 6] as Border).Visibility = Visibility.Hidden;
}

also i recommend to remove not to hide the child as it will otherwise stay in existance without any point

myGrid.Children.Remove(myGrid.Children[0]);