如何使属性网格(PropertyGrid)显示一个保存文件对话框(SaveFileDialog)?

4

我有一个属性网格控件,我希望在用户导出数据到新文件的过程中能够显示SaveFileDialog。我可以很容易地使用FileNameEditor连接OpenFileDialog,但似乎没有相应的类用于保存文件。

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

3个回答

7

这个很好用:

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;
    }
}

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; }
    }

为了让 Stewy的答案能够起作用 :) 在运行时,当您编辑此属性时,省略号将显示,然后您就可以选择一个文件进行“另存为”。

0

我认为没有现成的。你需要编写自己的编辑器,从UITypeEditor派生。这应该不难。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接