问题
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