我有一個系結了一些類屬性的 PropertyGrid。每個屬性都有一個EditorAttribute我定義了一個自定義類來進行更改的地方。我的愿望是使字串屬性只能通過此編輯器類進行編輯,而不是通過 PropertyGrid 文本欄位進行編輯。
我嘗試將其ReadOnly-attribute 更改為true,然后在我的編輯器類中更改此值,然后在使用反射的屬性設定器方法中將其重置,但這無法正常作業,因為文本欄位保持在焦點模式,我仍然可以進行更改。此外,對我來說,這更像是一種解決方法,而不是可接受的解決方案。
有沒有辦法只能通過EditorComponent-class 而不是 PropertyGrid 訪問我的屬性的設定器?
我的自定義編輯器類:
public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
{
using (EditorForm f = new Forms.EditorForm(value.ToString()))
{
if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
PropertyDescriptor descriptor = context.PropertyDescriptor;
if (descriptor != null)
{
ReadOnlyAttribute attribute = descriptor.Attributes[typeof(ReadOnlyAttribute)] as ReadOnlyAttribute;
if (attribute != null)
{
System.Reflection.FieldInfo fieldToChange = attribute.GetType().GetField("isReadOnly", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
if (fieldToChange != null)
{
fieldToChange.SetValue(attribute, false); // setting it to false
value = f.Text;
}
}
}
}
}
return value;
}
在此之后,我在我的 setter 方法中重新更改它:
private string _myText = String.Empty;
[Editor(typeof(...), typeof(UITypeEditor)),
ReadOnly(true)]
public string MyText
{
get { return _myText; }
set
{
_myText = value;
PropertyDescriptor descriptor = TypeDescriptor.GetProperties(this)["MyText"];
if (descriptor != null)
{
ReadOnlyAttribute attribute = descriptor.Attributes[typeof(ReadOnlyAttribute)] as ReadOnlyAttribute;
if (attribute != null)
{
System.Reflection.FieldInfo fieldToChange = attribute.GetType().GetField("isReadOnly", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
if (fieldToChange != null)
fieldToChange.SetValue(attribute, true); // resetting it to true
}
}
}
}
uj5u.com熱心網友回復:
您可以添加額外TypeConverter的內容以防止編輯(通過丟棄從字串到destinatino 型別的任何轉換(甚至destination 也是字串))。
ReadOnlyAttribute在此之后,您可以通過在 rutime 中進行編輯來洗掉所有連接的東西。
public class TestClass
{
[Editor(typeof(CustomEditor), typeof(UITypeEditor))]
[TypeConverter(typeof(ReadOnlyConverter))]
public string MyText { get; set; }
}
public class ReadOnlyConverter : TypeConverter
{
//just empty class
}
public class CustomEditor : UITypeEditor
{
public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
=> UITypeEditorEditStyle.Modal;
public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
{
var strVal = value as string;
var svc = provider.GetService(typeof(IWindowsFormsEditorService)) as IWindowsFormsEditorService;
using (var editorForm = new EditorForm())
{
editorForm.Value = strVal;
svc.ShowDialog(editorForm);
value = editorForm.Value;
};
return value;
}
}
此外,您可能需要添加額外簽入EditValue以確保服務可用、輸入值是真實的string等等。
您還可以覆寫 的成員ReadOnlyConverter以顯式禁用字串轉換,而不依賴于默認實作。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/432580.html
下一篇:如何參考ListBox項
