Search code examples
c#wpfexceptionuser-controlscode-behind

Exception: Do not call this method if VisualChildrenCount returns zero. When trying to change the Visibility of the User Control


I added a customized user control to a Window in WPF (C#). When I try to change the visibility of the control in code-behind, application throws the exception

System.ArgumentOutOfRangeException occurred Specified index is out of range or child at index is null. Do not call this method if VisualChildrenCount returns zero, indicating that the Visual has no children.

Edit: Relevant Code (Snippet out of the large code)

XAML:

<Window x:Class="TestClient.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:trend="clr-namespace:MultiseriesChartControl;assembly=MultipleLinesView"
        Title="MainWindow" Height="350" Width="525"
        Loaded="Window_Loaded">
    <Grid>
        <trend:MultipleLinesView x:Name="multipleLinesView"/>
    </Grid>
</Window>

Code-behind:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        MultipleLinesViewModel vModel = new MultipleLinesViewModel();
        Color sColor = Colors.Lime;
        multipleLinesView.CreateSeries("test", sColor, true);
        multipleLinesView.AttachData("test", ref vModel);

        MultipleLinesViewModel vModelTest = new MultipleLinesViewModel();
        Color tColor = Colors.MediumPurple;
        multipleLinesView.CreateSeries("test2", tColor, true);
        multipleLinesView.AttachData("test2", ref vModelTest);
    }
}

This is the MainWindow enter image description here

After clicking on the close button. Exception is thrown. And when continuing, UI becomes blank. enter image description here enter image description here


Solution

  • I think you’re calling the someFn method before the control is loaded. Don’t change the control’s visibility before the execution InitializeComponents() is completed.

    EDIT : As mentioned above, you were trying to set the UserControl’s visibility before that component is loaded. The reason for this is the code that you have mentioned in Windows_Loaded function is executed before InitializeComponents(). Hence when the close button is pressed, the data is not loaded into the usercontrol and hence the ex.

    Fix : To fix the issue, just move the code in Window_Loaded to the Constructor after the call of InitializeComponents() as mentioned in the comment.