【发布时间】:2014-10-15 20:26:21
【问题描述】:
问题
我想将一个引用的控件从主窗口加载到一个新窗口中。引用的控件已经是主窗口的子窗口,在尝试渲染新窗口时会导致以下异常:
System.ArgumentException 未处理:
在附加到新的父 Visual 之前,必须断开指定子与当前父 Visual 的连接。
我不想断开它与主窗口的连接,我也无法创建控件的新实例,因为我不知道它是如何实例化的或应用了哪些成员。
背景
我正在开发一个应用程序,它允许开发人员使用配置选项的附加视图来扩展应用程序。这些视图的容器对于大型视图扩展来说可能太小(想象一个日程安排控件作为示例),所以我希望为用户提供在新窗口中打开扩展视图的能力。
代码
到目前为止,我已经创建了一个附加到超链接的行为,该行为会在 Click 事件时打开一个带有引用控件的新窗口。以下代码是展示我意图的最基本的实现:
public class ExpandViewBehavior : Behavior<Hyperlink>
{
public static DependencyProperty ViewProperty = DependencyProperty.Register("View", typeof(object), typeof(ExpandViewBehavior));
public object View
{
get { return GetValue(ViewProperty); }
set { SetValue(ViewProperty, value); }
}
protected override void OnAttached()
{
this.AssociatedObject.Click += AssociatedObject_Click;
}
void AssociatedObject_Click(object sender, RoutedEventArgs e)
{
if (View != null)
{
var window = new Window()
{
Content = View
};
window.Show();
}
}
}
附加到主窗口中的Hyperlink,引用一个简单的TextBox 以在新窗口中加载。其中i 是System.Windows.Interactivity 命名空间,local 我的项目命名空间。
xmlns:local="clr-namespace:WpfApplication"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
...
<StackPanel>
<TextBlock>
<Hyperlink>
<i:Interaction.Behaviors>
<local:ExpandViewBehavior
View="{Binding Source={x:Reference SomeControl}}" />
</i:Interaction.Behaviors>
<TextBlock
Text="(Open in new window)" />
</Hyperlink>
</TextBlock>
<TextBox
x:Name="SomeControl" />
</StackPanel>
我的问题是,有没有一种方法可以在不断开与主窗口的连接的情况下加载引用的控件?
【问题讨论】:
-
噗,我不知道我为什么想这么复杂。我所要做的就是使用
DataTemplate将视图与DataContext关联起来。无论如何,它没有回答我提出的问题,@Alan 的回答可以。