WPF用户控件没有';我不能出现在网格中

WPF用户控件没有';我不能出现在网格中,wpf,grid,user-controls,Wpf,Grid,User Controls,我试图在WPF中将UserControl添加到网格中,但当我试图通过MyGrid.Children.add(UserControl)添加时,它没有显示出来。所以我试图显示我的网格中的child数,添加usercontrol后显示为1。(MyGrid.Children.Clear()也不起作用。清除网格后,它会说剩下0个孩子,但在编译程序时仍有一些UiElements。) 此问题仅出现在1个函数中。在另一个函数(同一个类)中,我可以轻松地将child添加到同一个网格(myGrid) 我的代码:

我试图在WPF中将UserControl添加到网格中,但当我试图通过MyGrid.Children.add(UserControl)添加时,它没有显示出来。所以我试图显示我的网格中的child数,添加usercontrol后显示为1。(MyGrid.Children.Clear()也不起作用。清除网格后,它会说剩下0个孩子,但在编译程序时仍有一些UiElements。)

此问题仅出现在1个函数中。在另一个函数(同一个类)中,我可以轻松地将child添加到同一个网格(myGrid)

我的代码:

        private void AddDateOnClick(object sender, MouseButtonEventArgs e)
        {
             MyGrid.Children.Clear();           
             UserControlAddDate ucad = new UserControlAddDate();
             MyGrid.Children.Add(ucad);
             MessageBox.Show(MyGrid.Children.Count.ToString());  //Only to test if there are some childs
        }

当我尝试在其他函数(同一类)中清除此网格时,它会清除网格。只有在这个函数中清除是一个问题。我不明白为什么???

这个UserControlAddDate是什么?可能它没有初始化。这就是为什么它没有被添加到网格中。。 在那个地方,尝试向网格中添加一个文本框,并检查它是否工作。如果它能工作,那就是代码的问题

正如Ed Plunkett提到的,请尝试使用模板和数据绑定。这是使用WPF的最佳方式

无论如何,试试这个

private void AddDateOnClick(object sender, MouseButtonEventArgs e)
{
     MyGrid.Children.Clear();           
     TextBox ucad = new TextBox();
     ucad.Text = “TEST”;
     MyGrid.Children.Add(ucad);
     MessageBox.Show(MyGrid.Children.Count.ToString());  //Only to test if there are some childs
}

这个UserControlAddDate是什么?可能它没有初始化。这就是为什么它没有被添加到网格中。。 在那个地方,尝试向网格中添加一个文本框,并检查它是否工作。如果它能工作,那就是代码的问题

正如Ed Plunkett提到的,请尝试使用模板和数据绑定。这是使用WPF的最佳方式

无论如何,试试这个

private void AddDateOnClick(object sender, MouseButtonEventArgs e)
{
     MyGrid.Children.Clear();           
     TextBox ucad = new TextBox();
     ucad.Text = “TEST”;
     MyGrid.Children.Add(ucad);
     MessageBox.Show(MyGrid.Children.Count.ToString());  //Only to test if there are some childs
}

使用模板和数据绑定。不要浪费时间与框架抗争。使用模板和数据绑定。不要浪费时间与框架抗争。