在我的 CodeBehind 中有以下内容(类名 MainHostWindow)
private object _hostContent = null;
public object HostContent
{
get { return _hostContent; }
set { _hostContent = value;}
}
这绑定(bind)到我的 View 的 ContentControl 中。
在不同的类(class)中,我执行以下操作:
MainHostWindow host = new MainHostWindow();
{
host.HostContent = MyView; // this is an instance of a UserControl
host.Owner = this._mainWindow;
host.DataContext = viewModel;
}
host.ShowDialog();
第一次显示具有正确内容的 MainHostWindow,第二次出现以下异常:
Specified element is already the logical child of another element. Disconnect it first.
最佳答案
看起来好像您正在尝试将相同的 UserControl(不是它的新实例)添加到 MainHostWindow 的另一个实例。错误是正确的,因为同一个元素不能是两个不同容器的子元素(UserControl.Parent 返回什么?)。您将需要创建一个新的 UserControl 实例。
host.HostContent = new MyView();
您是否能够在 MainHostWindow 的 XAML 中以声明方式设置 MyView,因为这将始终在创建控件时创建一个新实例。
关于wpf - 第二次尝试将内容绑定(bind)到窗口时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5385613/