我为WPF中的小团队制作了一个可重复使用的控件:一个我们经常使用的简单Dialog。 窗口的处理是通过私有方法完成的:
private static void ExecuteInternal(
Window owner,
string windowTitle,
string label,
object operation,
MyDialogSettings settings)
{
MyDialog dialog = new MyDialog(windowTitle, settings);
dialog.Owner = owner;
dialog.Label = label;
ShowDialog();
}
公开调用有System.Windows.Window
作为参数( - > WPF窗口),我的函数将Owner
设置为此窗口。
现在,我的同事希望从Windows窗体应用程序中使用此窗口。
我的第一个想法是用表单重载公共函数调用,然后在内部用WindowInteropHelper
处理它(参见:http://blogs.msdn.com/b/mhendersblog/archive/2005/10/04/476921.aspx)
但是我必须在每个使用我的库的(WPF)项目中引用Windows.Forms
。
因为我无法从Window外部访问窗口实例,所以WindowInteropHelper-thing无法在Forms应用程序中完成。
有什么想法吗?
答案 0 :(得分:0)
我用这种方法看到的问题是可重用控件根本不可重复使用。正如您所注意到的,main方法使用的是仅在其他任何地方都无法使用的WPF类型,因此现在无法重用WinForms。
为了能够这样做,您需要将对话框窗口的主要逻辑和视觉效果提取到用户控件中(因此它可以在WinForms中托管)。这是我要做的第一件事:
<UserControl .......>
<Grid>
<!-- Other controls you have on the dialog -->
<Button Content="Accept"/>
</Grid>
</UserControl>
非常简单,只需将所有内容移动到用户控件即可。然后,只需包含此控件,窗口本身就变得微不足道了:
<Window .......>
<controls:MyDialogContent ..../>
</Window>
到目前为止,没有任何变化,您发布的方法与以前完全相同。我们将其保留为仅WPF,并为WinForms实现几乎相同的方法。
在WinForms项目中,现在您必须创建将取代MyDialog
的表单。这个表单可以像WPF版本一样简单,只是一个ElementHost,它将包含您之前分离的UserControl,可能包含逻辑所需的任何属性/方法。
最后一部分是提供一个WinForms方法来调用它,类似于WPF方法。这可能就像这样简单:
private static void ExecuteInternal(Form owner,
string windowTitle,
string label,
object operation,
MyDialogSettings settings)
{
MyDialogForm dialog = new MyDialogForm(windowTitle, settings);
dialog.Owner = owner;
dialog.Label = label;
dialog.ShowDialog();
}