How to capture selected values from a dialog?
I created a FontDialog.cs Windows Form where my users can choose colors among other things for the text. I need to capture what the user has selected on the dialog:
Here's how I'm calling the dialog:
DialogsTestingGro开发者_JS百科unds.FontDialog dialog = new FontDialog();
dialog.ShowDialog();
How can I capture the selected values, I imagine I have to create properties for everything I want to transfer on the FontDialog.cs form end, right?
What you would want to do is expose properties on your FontDialog that make the values available. You could then use dialog.PropertyName to reference it by the name of the property.
It is not necessary, you can use, ie, dialog.Font to get the selected font, dialog.Color for the color and so on...
Mitchel's answer will work but you might want to incorporate a couple other items along the same line.
- Have a public property (per Mitchel's answer).
- Have a public constructor on your form with the type of the property as an argument so you can pass in the value in question (this would allow you have the dialog prepopulated with old selection).
- Surround your call to your dialog with a check for dialogresult so you only change the value when the user wants to. (note the process for this is different in WPF)
- Felice is also right in that you don't really need to create a new font dialog if the only thing you care about is the font. There is a built in font dialog in .Net http://msdn.microsoft.com/en-us/library/system.windows.forms.fontdialog%28v=vs.71%29.aspx
So the internals of your dialog class may look like this psuedo code.
public Font SelectedFont { get; set; }
public FontDialog()
{
//set your defaults here
}
public FontDialog (Font font)
{
SelectedFont = font;
//dont forget to set the passed in font to your ui values here
}
private void acceptButton_Click(object sender, EventArgs e)
{
SelectedFont = //How ever you create your font object;
}
Then to call your function (assumes the the acceptButton above is the forms AcceptButton)
DialogsTestingGrounds.FontDialog dialog = new FontDialog();
if(dialog.ShowDialog() == DialogResult.OK)
//Do Something
精彩评论