我正在制作一些自定義控制元件和用戶控制元件。其中一個派生自Labelwhich 公開一個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"; ;
}
}
uj5u.com熱心網友回復:
在測驗了這個場景之后(當雙擊 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;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/531010.html
