Visual Studio加载设计表单

发布于 2024-08-20 10:31:20 字数 13270 浏览 2 评论 0原文

当您有一个继承自 Forms 的类,然后让所有表单继承自 Class,然后尝试在 Visual Studio 中以设计模式加载表单时,是否有人遇到过问题?它加载是否正确,因为在我的上它显示“路径中的非法字符。”。 我在调试模式下运行 Visual Studio,发现它尝试检查我认为的文件的路径并获取通用定义的“>”。 那么是否可以在 Windows 窗体上实现泛型,或者我是否必须为此找到解决方法,我已经在互联网上搜索了一些示例或线索,但可以找到任何重要的示例或线索。任何指针将不胜感激,因为应用程序运行良好,但不是 Visual Studio 的设计模式。 谢谢。

基类

public class BaseForm<T, TU> : Form, IFormLanguageStrings
        where T : class
        where TU : class
    {
        #region Variables

        public IApplicationValues applicationValues;
        public T businessObject;
        public IEventBroker eventBroker;
        private bool hasChangesToCommit = false;
        public ILanguageManager languageManager;
        public IMessageBox messageBox;
        public TU objService;
        public DatabaseOperationType operationType;
        public event EventHandler OnNeedToCommitChanges;

        #endregion

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="BaseForm"/> class.
        /// </summary>
        public BaseForm()
        {
            Closing += BaseForm_Closing;
            Load += BaseForm_Load;
            if (IsInDesignMode) return;
            SetService();
        }

        #endregion

        #region Form Events

        /// <summary>
        /// Handles the Load event of the BaseForm control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void BaseForm_Load(object sender, EventArgs e)
        {
            if (IsInDesignMode) return;
            SetLabels();
            SetControls();
            LoadCombos();
            LoadDataForForm();
            ValidateDataInput();

            if (operationType == DatabaseOperationType.View)
            {
                eventBroker.Unregister(this);
                DisableAllControls();
                InvisibleSelectControls("BtnAction");
            }
        }

        /// <summary>
        /// Handles the Closing event of the BaseForm control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.ComponentModel.CancelEventArgs"/> instance containing the event data.</param>
        private void BaseForm_Closing(object sender, CancelEventArgs e)
        {
            if (hasChangesToCommit)
            {
                if (
                    messageBox.ShowQuestion(languageManager.GetString("MSG_PerformPendingOperations"),
                                            MessageBoxButton.YesNo, MessageBoxResult.No) == MessageBoxResult.Yes)
                {
                    RaiseCommitChanges();
                }
            }
            if (eventBroker != null)
                eventBroker.Unregister(this);
        }

        #endregion

        #region Virtual Methods

        /// <summary>
        /// Sets the labels.
        /// </summary>
        public virtual void SetLabels()
        {
            Controls.All().OfType<Control>().ToList().ForEach(
                ctl =>
                    {
                        if (!string.IsNullOrEmpty(ctl.Name))
                        {
                            string label = languageManager.GetString(ctl.Name);
                            if (!string.IsNullOrEmpty(label))
                            {
                                ctl.Text = label;
                            }
                            if (ctl is ElementHost)
                            {
                                if (((ElementHost) ctl).Child is IFormLanguageStrings)
                                {
                                    (((ElementHost) ctl).Child as IFormLanguageStrings).SetLabels();
                                }
                            }
                        }
                    });
        }

        /// <summary>
        /// Sets the service.
        /// </summary>
        public virtual void SetService()
        {
            applicationValues = ServiceGateway.GetService<IApplicationValues>();
            languageManager = ServiceGateway.GetService<ILanguageManager>();
            messageBox = ServiceGateway.GetService<IMessageBox>();
            eventBroker = ServiceGateway.GetService<IEventBroker>();
            eventBroker.Register(this);
            objService = ServiceGateway.GetService<TU>();
        }

        /// <summary>
        /// Validates the data input.
        /// </summary>
        public virtual void ValidateDataInput()
        {
        }

        /// <summary>
        /// Determines whether [has to commit changes] [the specified commit].
        /// </summary>
        /// <param name="commit">if set to <c>true</c> [commit].</param>
        public virtual void HasToCommitChanges(bool commit)
        {
            switch (operationType)
            {
                case DatabaseOperationType.Update:
                    hasChangesToCommit = commit;
                    break;
            }
        }

        /// <summary>
        /// Loads the combos.
        /// </summary>
        public virtual void LoadCombos()
        {
        }

        /// <summary>
        /// Loads the data for form.
        /// </summary>
        public virtual void LoadDataForForm()
        {
        }

        /// <summary>
        /// Sets the controls.
        /// </summary>
        public virtual void SetControls()
        {
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// Raises the commit changes.
        /// </summary>
        private void RaiseCommitChanges()
        {
            if (OnNeedToCommitChanges != null)
            {
                OnNeedToCommitChanges(this, EventArgs.Empty);
            }
        }

        /// <summary>
        /// Closes the form.
        /// </summary>
        protected void CloseForm()
        {
            FireEventBroker(EventTopics.CloseMdiChild, new CloseMdiChildEventArgs(this));
        }

        /// <summary>
        /// Enables or disable controls.
        /// </summary>
        /// <typeparam name="T">type of control</typeparam>
        /// <param name="isEnable">if set to <c>true</c> [is enable].</param>
        private void EnableDisableControls<TX>(bool isEnable) where TX : Control
        {
            Controls.All()
                .OfType<TX>()
                .ToList()
                .ForEach(ctl => ctl.Enabled = isEnable);
        }

        /// <summary>
        /// Visibles or invisible all controls.
        /// </summary>
        /// <param name="isVisible">if set to <c>true</c> [is visible].</param>
        private void VisibleInvisibleAllControls(bool isVisible)
        {
            Controls.All()
                .OfType<Control>()
                .ToList()
                .ForEach(ctl => ctl.Visible = isVisible);
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// Gets a value indicating whether this instance is in design mode.
        /// </summary>
        /// <value>
        ///     <c>true</c> if this instance is in design mode; otherwise, <c>false</c>.
        /// </value>
        public bool IsInDesignMode
        {
            get { return (Process.GetCurrentProcess().ProcessName == "devenv"); }
        }

        /// <summary>
        /// Fires the event broker.
        /// </summary>
        /// <param name="eventTopic">The event topic.</param>
        /// <param name="eventArgs">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        public void FireEventBroker(string eventTopic, EventArgs eventArgs)
        {
            eventBroker.Fire(eventTopic, this, eventArgs);
        }

        /// <summary>
        /// Clears all bindings.
        /// </summary>
        public void ClearAllBindings()
        {
            Controls.All().OfType<Control>().ToList().ForEach(
                ctl => { if (ctl.DataBindings.Count != 0) ctl.DataBindings.Clear(); });
        }

        /// <summary>
        /// Enables all controls.
        /// </summary>
        public void EnableAllControls()
        {
            EnableDisableAllControls(true);
        }

        /// <summary>
        /// Disables all controls.
        /// </summary>
        public void DisableAllControls()
        {
            EnableDisableAllControls(false);
        }

        /// <summary>
        /// Enables or disable all controls.
        /// </summary>
        /// <param name="isEnable">if set to <c>true</c> [is enable].</param>
        private void EnableDisableAllControls(bool isEnable)
        {
            Controls.All()
                .OfType<Control>()
                .ToList()
                .ForEach(ctl => ctl.Enabled = isEnable);
        }

        /// <summary>
        /// Enables all buttons.
        /// </summary>
        public void EnableAllButtons()
        {
            EnableDisableControls<Button>(true);
        }

        /// <summary>
        /// Disables all buttons.
        /// </summary>
        public void DisableAllButtons()
        {
            EnableDisableControls<Button>(false);
        }

        /// <summary>
        /// Enables all text boxes.
        /// </summary>
        public void EnableAllTextBoxes()
        {
            EnableDisableControls<TextBox>(true);
        }

        /// <summary>
        /// Disables all text boxes.
        /// </summary>
        public void DisableAllTextBoxes()
        {
            EnableDisableControls<TextBox>(false);
        }

        /// <summary>
        /// Enables the select controls.
        /// </summary>
        /// <param name="controlNames">The control names.</param>
        public void EnableSelectControls(params string[] controlNames)
        {
            EnableDisableSelectedControls(true, controlNames);
        }

        /// <summary>
        /// Disables the select controls.
        /// </summary>
        /// <param name="controlNames">The control names.</param>
        public void DisableSelectControls(params string[] controlNames)
        {
            EnableDisableSelectedControls(false, controlNames);
        }

        /// <summary>
        /// Enables or disable selected controls.
        /// </summary>
        /// <param name="isEnable">if set to <c>true</c> [is enable].</param>
        /// <param name="controlNames">The control names.</param>
        public void EnableDisableSelectedControls(bool isEnable, params string[] controlNames)
        {
            Controls.All()
                .OfType<Control>()
                .ToList()
                .ForEach(ctl => { if (controlNames.Contains(ctl.Name)) ctl.Enabled = isEnable; });
        }

        /// <summary>
        /// Visibles the select controls.
        /// </summary>
        /// <param name="controlNames">The control names.</param>
        public void VisibleSelectControls(params string[] controlNames)
        {
            VisibleInvisibleSelectedControls(true, controlNames);
        }

        /// <summary>
        /// Invisibles the select controls.
        /// </summary>
        /// <param name="controlNames">The control names.</param>
        public void InvisibleSelectControls(params string[] controlNames)
        {
            VisibleInvisibleSelectedControls(false, controlNames);
        }

        /// <summary>
        /// Visibles or invisible selected controls.
        /// </summary>
        /// <param name="isVisible">if set to <c>true</c> [is visible].</param>
        /// <param name="controlNames">The control names.</param>
        private void VisibleInvisibleSelectedControls(bool isVisible, params string[] controlNames)
        {
            Controls.All()
                .OfType<Control>()
                .ToList()
                .ForEach(ctl => { if (controlNames.Contains(ctl.Name)) ctl.Visible = isVisible; });
        }

        /// <summary>
        /// Visibles all controls.
        /// </summary>
        public void VisibleAllControls()
        {
            VisibleInvisibleAllControls(true);
        }

        /// <summary>
        /// Invisibles all controls.
        /// </summary>
        public void InvisibleAllControls()
        {
            VisibleInvisibleAllControls(false);
        }

        #endregion
    }
}

Does anyone came across a problem when you have a Class that inherits from Forms and then have all the forms inherit from Class, and then tried to load the form in design mode in visual studio? Does it loads correctly, because on mine it shows "Illegal characters in path.".
I ran the visual studio in debug mode and found that it is try to check a path for the file I suppose and gets the ´>´ of the generic definition.
So is it possible to implement generics over windows forms or do I have to get a workaround for this, I have searched the internet for some examples or clues where to follow but could find any important one. Any pointers would be much appreciated, because the application works runs fine but not the design mode of visual studio.
Thanks.

Base class

public class BaseForm<T, TU> : Form, IFormLanguageStrings
        where T : class
        where TU : class
    {
        #region Variables

        public IApplicationValues applicationValues;
        public T businessObject;
        public IEventBroker eventBroker;
        private bool hasChangesToCommit = false;
        public ILanguageManager languageManager;
        public IMessageBox messageBox;
        public TU objService;
        public DatabaseOperationType operationType;
        public event EventHandler OnNeedToCommitChanges;

        #endregion

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="BaseForm"/> class.
        /// </summary>
        public BaseForm()
        {
            Closing += BaseForm_Closing;
            Load += BaseForm_Load;
            if (IsInDesignMode) return;
            SetService();
        }

        #endregion

        #region Form Events

        /// <summary>
        /// Handles the Load event of the BaseForm control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void BaseForm_Load(object sender, EventArgs e)
        {
            if (IsInDesignMode) return;
            SetLabels();
            SetControls();
            LoadCombos();
            LoadDataForForm();
            ValidateDataInput();

            if (operationType == DatabaseOperationType.View)
            {
                eventBroker.Unregister(this);
                DisableAllControls();
                InvisibleSelectControls("BtnAction");
            }
        }

        /// <summary>
        /// Handles the Closing event of the BaseForm control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.ComponentModel.CancelEventArgs"/> instance containing the event data.</param>
        private void BaseForm_Closing(object sender, CancelEventArgs e)
        {
            if (hasChangesToCommit)
            {
                if (
                    messageBox.ShowQuestion(languageManager.GetString("MSG_PerformPendingOperations"),
                                            MessageBoxButton.YesNo, MessageBoxResult.No) == MessageBoxResult.Yes)
                {
                    RaiseCommitChanges();
                }
            }
            if (eventBroker != null)
                eventBroker.Unregister(this);
        }

        #endregion

        #region Virtual Methods

        /// <summary>
        /// Sets the labels.
        /// </summary>
        public virtual void SetLabels()
        {
            Controls.All().OfType<Control>().ToList().ForEach(
                ctl =>
                    {
                        if (!string.IsNullOrEmpty(ctl.Name))
                        {
                            string label = languageManager.GetString(ctl.Name);
                            if (!string.IsNullOrEmpty(label))
                            {
                                ctl.Text = label;
                            }
                            if (ctl is ElementHost)
                            {
                                if (((ElementHost) ctl).Child is IFormLanguageStrings)
                                {
                                    (((ElementHost) ctl).Child as IFormLanguageStrings).SetLabels();
                                }
                            }
                        }
                    });
        }

        /// <summary>
        /// Sets the service.
        /// </summary>
        public virtual void SetService()
        {
            applicationValues = ServiceGateway.GetService<IApplicationValues>();
            languageManager = ServiceGateway.GetService<ILanguageManager>();
            messageBox = ServiceGateway.GetService<IMessageBox>();
            eventBroker = ServiceGateway.GetService<IEventBroker>();
            eventBroker.Register(this);
            objService = ServiceGateway.GetService<TU>();
        }

        /// <summary>
        /// Validates the data input.
        /// </summary>
        public virtual void ValidateDataInput()
        {
        }

        /// <summary>
        /// Determines whether [has to commit changes] [the specified commit].
        /// </summary>
        /// <param name="commit">if set to <c>true</c> [commit].</param>
        public virtual void HasToCommitChanges(bool commit)
        {
            switch (operationType)
            {
                case DatabaseOperationType.Update:
                    hasChangesToCommit = commit;
                    break;
            }
        }

        /// <summary>
        /// Loads the combos.
        /// </summary>
        public virtual void LoadCombos()
        {
        }

        /// <summary>
        /// Loads the data for form.
        /// </summary>
        public virtual void LoadDataForForm()
        {
        }

        /// <summary>
        /// Sets the controls.
        /// </summary>
        public virtual void SetControls()
        {
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// Raises the commit changes.
        /// </summary>
        private void RaiseCommitChanges()
        {
            if (OnNeedToCommitChanges != null)
            {
                OnNeedToCommitChanges(this, EventArgs.Empty);
            }
        }

        /// <summary>
        /// Closes the form.
        /// </summary>
        protected void CloseForm()
        {
            FireEventBroker(EventTopics.CloseMdiChild, new CloseMdiChildEventArgs(this));
        }

        /// <summary>
        /// Enables or disable controls.
        /// </summary>
        /// <typeparam name="T">type of control</typeparam>
        /// <param name="isEnable">if set to <c>true</c> [is enable].</param>
        private void EnableDisableControls<TX>(bool isEnable) where TX : Control
        {
            Controls.All()
                .OfType<TX>()
                .ToList()
                .ForEach(ctl => ctl.Enabled = isEnable);
        }

        /// <summary>
        /// Visibles or invisible all controls.
        /// </summary>
        /// <param name="isVisible">if set to <c>true</c> [is visible].</param>
        private void VisibleInvisibleAllControls(bool isVisible)
        {
            Controls.All()
                .OfType<Control>()
                .ToList()
                .ForEach(ctl => ctl.Visible = isVisible);
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// Gets a value indicating whether this instance is in design mode.
        /// </summary>
        /// <value>
        ///     <c>true</c> if this instance is in design mode; otherwise, <c>false</c>.
        /// </value>
        public bool IsInDesignMode
        {
            get { return (Process.GetCurrentProcess().ProcessName == "devenv"); }
        }

        /// <summary>
        /// Fires the event broker.
        /// </summary>
        /// <param name="eventTopic">The event topic.</param>
        /// <param name="eventArgs">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        public void FireEventBroker(string eventTopic, EventArgs eventArgs)
        {
            eventBroker.Fire(eventTopic, this, eventArgs);
        }

        /// <summary>
        /// Clears all bindings.
        /// </summary>
        public void ClearAllBindings()
        {
            Controls.All().OfType<Control>().ToList().ForEach(
                ctl => { if (ctl.DataBindings.Count != 0) ctl.DataBindings.Clear(); });
        }

        /// <summary>
        /// Enables all controls.
        /// </summary>
        public void EnableAllControls()
        {
            EnableDisableAllControls(true);
        }

        /// <summary>
        /// Disables all controls.
        /// </summary>
        public void DisableAllControls()
        {
            EnableDisableAllControls(false);
        }

        /// <summary>
        /// Enables or disable all controls.
        /// </summary>
        /// <param name="isEnable">if set to <c>true</c> [is enable].</param>
        private void EnableDisableAllControls(bool isEnable)
        {
            Controls.All()
                .OfType<Control>()
                .ToList()
                .ForEach(ctl => ctl.Enabled = isEnable);
        }

        /// <summary>
        /// Enables all buttons.
        /// </summary>
        public void EnableAllButtons()
        {
            EnableDisableControls<Button>(true);
        }

        /// <summary>
        /// Disables all buttons.
        /// </summary>
        public void DisableAllButtons()
        {
            EnableDisableControls<Button>(false);
        }

        /// <summary>
        /// Enables all text boxes.
        /// </summary>
        public void EnableAllTextBoxes()
        {
            EnableDisableControls<TextBox>(true);
        }

        /// <summary>
        /// Disables all text boxes.
        /// </summary>
        public void DisableAllTextBoxes()
        {
            EnableDisableControls<TextBox>(false);
        }

        /// <summary>
        /// Enables the select controls.
        /// </summary>
        /// <param name="controlNames">The control names.</param>
        public void EnableSelectControls(params string[] controlNames)
        {
            EnableDisableSelectedControls(true, controlNames);
        }

        /// <summary>
        /// Disables the select controls.
        /// </summary>
        /// <param name="controlNames">The control names.</param>
        public void DisableSelectControls(params string[] controlNames)
        {
            EnableDisableSelectedControls(false, controlNames);
        }

        /// <summary>
        /// Enables or disable selected controls.
        /// </summary>
        /// <param name="isEnable">if set to <c>true</c> [is enable].</param>
        /// <param name="controlNames">The control names.</param>
        public void EnableDisableSelectedControls(bool isEnable, params string[] controlNames)
        {
            Controls.All()
                .OfType<Control>()
                .ToList()
                .ForEach(ctl => { if (controlNames.Contains(ctl.Name)) ctl.Enabled = isEnable; });
        }

        /// <summary>
        /// Visibles the select controls.
        /// </summary>
        /// <param name="controlNames">The control names.</param>
        public void VisibleSelectControls(params string[] controlNames)
        {
            VisibleInvisibleSelectedControls(true, controlNames);
        }

        /// <summary>
        /// Invisibles the select controls.
        /// </summary>
        /// <param name="controlNames">The control names.</param>
        public void InvisibleSelectControls(params string[] controlNames)
        {
            VisibleInvisibleSelectedControls(false, controlNames);
        }

        /// <summary>
        /// Visibles or invisible selected controls.
        /// </summary>
        /// <param name="isVisible">if set to <c>true</c> [is visible].</param>
        /// <param name="controlNames">The control names.</param>
        private void VisibleInvisibleSelectedControls(bool isVisible, params string[] controlNames)
        {
            Controls.All()
                .OfType<Control>()
                .ToList()
                .ForEach(ctl => { if (controlNames.Contains(ctl.Name)) ctl.Visible = isVisible; });
        }

        /// <summary>
        /// Visibles all controls.
        /// </summary>
        public void VisibleAllControls()
        {
            VisibleInvisibleAllControls(true);
        }

        /// <summary>
        /// Invisibles all controls.
        /// </summary>
        public void InvisibleAllControls()
        {
            VisibleInvisibleAllControls(false);
        }

        #endregion
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

尝蛊 2024-08-27 10:31:20

好吧,问题是“MyForm”设计器不起作用:

    public class MyForm : BaseForm<MyPresenter, MyView>
    {
        //designer doesn't work
    }

解决方法是创建辅助类:

    public class MyFormWithDesign : BaseForm<MyPresenter, MyView>
    {
        //designer doesn't work
    }

因此我们从辅助类而不是通用类派生:

    public class MyForm : MyFormWithDesign
    {
        //designer WORKS!
    }

有关该问题的其他详细信息可以在此处找到:
Windows 窗体设计器不能使用从通用类派生的组件

Ok so problem is that for "MyForm" designer doesn't work:

    public class MyForm : BaseForm<MyPresenter, MyView>
    {
        //designer doesn't work
    }

Workaround for this is to create helper class:

    public class MyFormWithDesign : BaseForm<MyPresenter, MyView>
    {
        //designer doesn't work
    }

so we derive from helper class and not from generic class:

    public class MyForm : MyFormWithDesign
    {
        //designer WORKS!
    }

Additional details about the problem can be found here:
Windows Form Designer can't use a component derived from a generic class

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文