窗体编辑器自动将子控件添加到 WPF Integration ElementHost



我正在尝试在WinForms应用程序中使用WPF TextBox,同时将WPF相关的详细信息完全封装在另一个程序集中,但窗体编辑器并没有使其变得简单。

也就是说,子访问器始终被分配给新的 System.Windows.Controls.TextBox,即使该访问器被替换为另一个数据类型,使用 new 并用各种属性来扼杀它,这些属性应该导致它被忽略。 删除该条目会导致表单编辑器重新生成该条目。

该值由控件本身分配,并且还破坏了我希望实现的封装。

有没有办法防止表单编辑器自动生成子项?

    // 
    // 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; } }
    }
}

编辑:

到目前为止,我找到了三种解决方法。 之所以添加在这里,是因为这些都不符合答案的条件。

  • 让窗体编辑器负责文本框的分配。

不可接受,因为上述希望封装 WPF 细节和程序集。

  • 根本不让表单编辑器管理组件。

充其量很烦人。 最好使用表单编辑器创建和管理组件。

  • 将TextBox_SpellCheck (ElementHost) 放在用户控件中。

只要窗体编辑器不重新生成 UserControl 的设计器代码(如果一开始不是手动生成的),就可以工作。 但是,这增加了一层不必要的控件嵌套。

更多信息:

删除TextBox_SpellCheck上的 Designer 属性会使情况变得更糟,导致在设计器代码中生成单独的托管组件。

使用不同的类型要么不会改善问题,要么会使事情变得更糟。

举几个例子:

  • ParentControlDesigner 仍生成子元素。
  • ScrollableControl 仍生成子元素。
  • 文档设计器引发导致窗体编辑器不可用的异常。
  • System.ComponentModel.Design.ComponentDesigner 将控件生成为间接可用的组件,例如通过窗体编辑器添加数据源或任何内容。

不确定如果你打算这样做,你会找到一种方法。 ElementHost 在设计上使用 Child 的确切原因 - 您将 WPF 元素托管在 Windows 窗体控件内。 它总是会生成你在设计器中不利的代码。

最新更新