使用OpenFileDialog设置属性值时,在PropertyGrid中取消选择自定义控件



我正在制作一些自定义控件和用户控件。其中一个来自Label,它公开了一个Image属性,用于显示SVG。

我的问题是在设计时,当我在PropertyGrid中设置SVG路径。在它从OpenFileDialog获得SVG文件路径后,它自动选择对话框下面的Form,因此PropertyGrid切换到Form的属性。

知道为什么会这样吗?

这是我的一部分代码…

public partial class LabelSVG : Label
{
private string svg_image_name     = null;
[Category("• SVG")]
[DisplayName("SVGImage •")]
[Description("...")]
[DefaultValue(null)]
[Browsable(true)]
[Editor(typeof(FileNameEditorSVG), typeof(UITypeEditor))]
public string SVGImage
{
get
{
return svg_image_name;
}
set
{
this.svg_image_name = Path.GetFileName(value); //[ Returns only the name of .svg file and its extension at property field. ]
this.SVGImage_Method(value); //[ Takes the full path of .svg file and do its stuff. ]
Invalidate();
}
}
private void SVGImage_Method(string value)
{
if (value != null) //[ This value is the full path of .svg file from "SVGImage" property. ]
{
if (File.Exists(value))
{
this.svg_image_path = value; //[ Stores the full path of .svg file for later use. ]
XmlDocument xml_document = new XmlDocument { XmlResolver = null };
xml_document.Load(value); //[ Loads the "XML Document" of .svg file. ]
this.svg_image_document = xml_document.InnerXml; //[ Stores the "Inner XML" of .svg file for later use. ]
this.SVGImageRender();
}
}
else
{
this.svg_image_path = null;
this.svg_image_document = null;
this.Image = null;
}
}
}
public class FileNameEditorSVG : FileNameEditor
{
protected override void InitializeDialog(OpenFileDialog open_file_dialog)
{
base.InitializeDialog(open_file_dialog);
open_file_dialog.Title = "Select an SVG File : ";
open_file_dialog.Filter = "SVG File (*.svg)|*.svg"; ;
}
}

在测试了这个场景之后(当在OpenFileDialog中双击一个文件时,窗体设计器中的一个不同的控件变得活动),似乎只需要重新选择控件,将其恢复为活动控件,这样PropertyGrid就可以选择正在编辑的属性。

从ITypeDescriptorContext对象中获取实例,然后调用Select()并在该实例上设置Capture = true(它代表拥有正在编辑的属性的控件)

你必须重写和重建UITypeEditor的EditValue方法——这里的类直接派生自UITypeEditor——以添加自定义行为(尽管你可能会摆脱标准实现):

public class FileNameEditorSVG : UITypeEditor {
private OpenFileDialog dialog = null;
protected virtual void InitializeDialog(OpenFileDialog ofd)
{
ofd.Title = "Select an SVG File: ";
ofd.Filter = "SVG File (*.svg)|*.svg";
}
public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) => UITypeEditorEditStyle.Modal;
public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
{
if (provider is null || provider.GetService(typeof(IWindowsFormsEditorService)) is null) {
return value;
}
var ctl = (Control)context.Instance;
if (dialog is null) {
dialog = new OpenFileDialog();
InitializeDialog(dialog);
}
if (value is string s) dialog.FileName = s;
if (dialog.ShowDialog() == DialogResult.OK) {
ctl.Select();
ctl.Capture = true; // PropertyGrid stuff
return dialog.FileName;
}
return value;
}
}

最新更新