例外:如果 VisualChildrenCount returns 为零,则不要调用此方法。尝试更改用户控件的可见性时

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

我在 WPF (C#) 中向 Window 添加了自定义用户控件。 当我尝试在代码隐藏中更改控件的可见性时,应用程序抛出异常

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.

编辑:相关代码(大代码片段)

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>

代码隐藏:

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);
    }
}

这是MainWindow

点击关闭按钮后。抛出异常。继续时,UI 变为空白。

我认为您在加载控件之前调用了 someFn 方法。 在执行 InitializeComponents() 完成之前不要更改控件的可见性。

编辑: 如上所述,您试图在加载该组件之前设置 UserControl 的可见性。 原因是您在 Windows_Loaded 函数中提到的代码在 InitializeComponents() 之前执行。因此,当按下关闭按钮时,数据不会加载到用户控件中,因此 ex.

Fix :要解决此问题,只需将 Window_Loaded 中的代码移动到 InitializeComponents() 调用后的 Constructor 中,如前所述在评论中。

里面直接加Window_Loaded

 if(multipleLinesView.IsLoaded){
    DoThings(...);
 }