当实例化的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();
}
}
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();
}
}