如何让PropertyGrid显示SaveFileDialog?

Ste*_*ewy 3 c# winforms

我有一个属性网格控件,我希望能够在用户正在将数据导出到新文件的过程中显示SaveFileDialog.我可以轻松地将OpenFileDialog与FileNameEditor挂钩,但似乎没有用于保存文件的等效类.

是否存在可以在System.ComponentModel.Editor属性中指定的现有类,以便显示SaveFileDialog?

Ste*_*ewy 8

这很好用:

public class SaveFileNameEditor: UITypeEditor
{
    public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
    {
        return UITypeEditorEditStyle.Modal;
    }

    public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
    {
        if (context == null || context.Instance == null || provider == null)
        {
            return base.EditValue(context, provider, value);
        }

        using (SaveFileDialog saveFileDialog = new SaveFileDialog())
        {
            if (value != null)
            {
                saveFileDialog.FileName = value.ToString();
            }

            saveFileDialog.Title = context.PropertyDescriptor.DisplayName;
            saveFileDialog.Filter = "All files (*.*)|*.*";
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                value = saveFileDialog.FileName;
            }
        }

        return value;
    }
}
Run Code Online (Sandbox Code Playgroud)


tzu*_*zup 5

因此,您在其中设置的对象propertyGrid1.SelectedObject需要一个公共属性,如下所示:

            private string _saveFile;
    [BrowsableAttribute(true)]
    [EditorAttribute(typeof(SaveFileNameEditor), typeof(System.Drawing.Design.UITypeEditor))]
    public string SaveFileEditorVlad
    {
        get { return _saveFile; }
        set { _saveFile = value; }
    }
Run Code Online (Sandbox Code Playgroud)

为了使Stewy的答案有效:)然后在运行时,当您编辑this属性时,将显示省略号,并且您可以选择一个文件另存为。