我试图在 WinForms 应用程序中使用 WPF 文本框,同时将与 WPF 相关的详细信息完全封装在另一个程序集中,但窗体编辑器并没有使它变得简单。
也就是说,Child 访问器总是被分配给一个新的 System.Windows.Controls.TextBox,即使该访问器被使用 new 的另一种数据类型替换并且被各种应该导致它被忽略的属性所掩盖。删除条目会导致表单编辑器重新生成它。
该值由控件本身分配,另外破坏了我希望实现的封装。
有没有办法阻止 Forms 编辑器自动生成 Child?
//
// textBox_SpellCheck1
//
this.textBox_SpellCheck1.Location = new System.Drawing.Point(12, 12);
this.textBox_SpellCheck1.Name = "textBox_SpellCheck1";
this.textBox_SpellCheck1.Size = new System.Drawing.Size(200, 100);
this.textBox_SpellCheck1.TabIndex = 0;
this.textBox_SpellCheck1.Text = "textBox_SpellCheck1";
//The Forms editor should not be generating the following line:
this.textBox_SpellCheck1.Child = new System.Windows.Controls.TextBox();
重现问题的示例,当它被放置在一个表单中时:
using System;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Controls; //reference PresentationCore, PresentationFramework
using System.Windows.Forms.Integration; //reference WindowsFormsIntegration
using System.Windows.Forms.Design;
namespace wtf
{
[Designer(typeof(ControlDesigner))] //reference System.Design
public class TextBox_SpellCheck : ElementHost
{
private System.Windows.Controls.TextBox textbox;
public TextBox_SpellCheck()
{
textbox = new System.Windows.Controls.TextBox();
base.Child = textbox;
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[EditorBrowsable(EditorBrowsableState.Never)]
[DefaultValue(0)]
public new int Child { set { } get { return 0; } }
}
}
编辑:
到目前为止,我发现了三种解决方法。添加到这里是因为这些都不符合答案的条件。
- 让表单编辑器负责 TextBox 的分配。
Not Acceptable ,由于上述对 WPF 细节和程序集的封装的愿望。
- 不要让表单编辑器管理组件。
充其量是烦人的。最好使用表单编辑器创建和管理组件。
- 将 TextBox_SpellCheck (ElementHost) 放在 UserControl 中。
只要窗体编辑器不为 UserControl 重新生成设计器代码,就可以工作,如果不是首先手动构建的话。然而,这增加了一层不必要的控件嵌套。
更多信息:
删除 TextBox_SpellCheck 上的 Designer 属性会使事情变得更糟,导致在设计器代码中生成单独的托管组件。
使用不同的类型要么不会改善问题,要么会使事情变得更糟。
几个例子:
- ParentControlDesigner 仍然生成子元素。
- ScrollableControl 仍然生成子元素。
- DocumentDesigner 引发异常,导致表单编辑器无法使用。
- System.ComponentModel.Design.ComponentDesigner 将控件生成为可间接使用的组件,例如通过表单编辑器添加数据源或其他内容。
最佳答案
不确定是否会找到一种方法,如果您打算这样做的话。 ElementHost 在设计上使用 Child 的原因与您使用它的确切原因相同——您在 Windows 窗体控件中托管一个 WPF 元素。它总是会生成您在设计器中不喜欢的代码。
关于c# - 表单编辑器自动将子控件添加到 WPF Integration ElementHost,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18898916/