Making a Form as a reusable Control like FolderBrowser

末鹿安然 提交于 2020-01-17 05:36:07

问题


I have created a form that emulates a FolderBrowseDialog, but with some added features I wanted. It's tested and working, so now I want to make it into a control. My problem is that as soon as I inherit from UserControl instead of Form, I no longer have a Close() method, and I no longer have a FormClosing event. When I click on the OK or Cancel button, how do I close the form and return control to the calling object?


回答1:


To make it a reusable component, instead of trying to derive it from Control, create a Component which uses that form. This way it can show in toolbox and you can drop an instance of your component on design surface like other components.

Your component should contain some properties which you want to expose from the dialog, also contain a ShowDialog method which created your form using some properties (like title, initial directory) and the shows your custom form as dialog and sets some properties (like selected folder) and returns the dialog result. For example:

using System.ComponentModel;
using System.Windows.Forms;
public partial class MyFolderBrowser : Component
{
    public string Text { get; set; }
    public string SelectcedFolder { get; set; }
    public DialogResult ShowDialog()
    {
        using (var f = new YourCustomForm() { Text = this.Text })
        {
            var result = f.ShowDialog();
            if (result == DialogResult.OK)
                SelectcedFolder = f.SelectedFolder;
            return result;
        }
    }
}


来源:https://stackoverflow.com/questions/40077060/making-a-form-as-a-reusable-control-like-folderbrowser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!