WPF学习笔记 - ”指定的元素已经是另一个元素的逻辑子元素。请先将其断开连接。“问题的解决方法之一

当实例化的UserControl作为多个父类控件的Content内容时,如果不清除他与前一个父控件的关系,则会报此类错误,解决办法是,再重新作为新的父控件的Content之前,清除UserControl的父类绑定即可,下面是一个例子中第8行到第12行的代码为清除绑定:
        public void InsertExecuted()
        {
            if (this.DetailView != null)
            {
                Window window = new Window();
                window.DataContext = new MasterDetailDataModel();
                UserControl uc = (UserControl)this.DetailView;
                DependencyObject parent = uc.Parent;
                if (parent != null)
                {
                    parent.SetValue(ContentPresenter.ContentProperty, null);
                }
                window.Content = uc;
                window.ShowDialog();
                
            }
        }


你可能感兴趣的:(编程应用点滴)