PropertyGrid control and drop-down lists - c#

I wanted to create a drop-down list as the editor for a property; If I had only strings as entries for the dropdown list, this would work fine (Using a StringConverter). However, when I tried to use a list of objects instead of Strings, this would not work (note how it works for normal comboboxes however!)
This was my code:
public static List<Bar> barlist;
public Form1()
{
InitializeComponent();
barlist = new List<Bar>();
for (int i = 1; i < 10; i++)
{
Bar bar = new Bar();
bar.barvalue = "BarObject " + i;
barlist.Add(bar);
comboBox1.Items.Add(bar);
}
Foo foo = new Foo();
foo.bar = new Bar();
propertyGrid1.SelectedObject = foo;
}
public class Foo
{
Bar mybar;
[TypeConverter(typeof(BarConverter))]
public Bar bar
{
get { return mybar; }
set { mybar = value; }
}
}
public class Bar
{
public String barvalue;
public override String ToString()
{
return barvalue;
}
}
class BarConverter : TypeConverter
{
public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
{
return true;
}
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
{
return new StandardValuesCollection(barlist);
}
}
The result (embedded into a form etc) looked like this:
Clicking an entry gave me this:
(Sorry about the german text, I am not sure if I can change that, my VS is english but my OS isnt, the error message is
Invalid property value.
The object of type "System.String" cannot be converted to type
"XMLTest.Form1+Bar".
I am pretty sure I can do a workaround for this by defining backwards conversion tools that convert a string back into a Bar object. This would require the keys being different in order to make this work properly. Is there a nicer way of doing this? Why does the comboBox that is embedded into the propertyGrid control use Strings (the normal comboBox has no problems whatsoever dealing with this)
On top of that, can I change the position of the middle separator programmatically? I have yet to find that option.
Thank you.

I added the CanConvertFrom and ConvertFrom methods to your conversion class:
class BarConverter : TypeConverter
{
public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
{
return true;
}
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
{
return new StandardValuesCollection(barlist);
}
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof(string))
{
return true;
}
return base.CanConvertFrom(context, sourceType);
}
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
if (value is string)
{
foreach (Bar b in barlist)
{
if (b.barvalue == (string)value)
{
return b;
}
}
}
return base.ConvertFrom(context, culture, value);
}
}

Related

How to save a struct property of a user control in Windows Forms Designer?

I've checked the answers of this question:
Modifying structure property in a PropertyGrid
And also SizeConverter from .net.
But not helpful, my property is still not saved.
I have a struct, a user control, and a custom type converter.
public partial class UserControl1 : UserControl
{
public Bar bar { get; set; } = new Bar();
}
[TypeConverter(typeof(BarConverter))]
public struct Bar
{
public string Text { get; set; }
}
public class BarConverter : ExpandableObjectConverter
{
public override bool GetCreateInstanceSupported(ITypeDescriptorContext context)
{
return true;
}
public override object CreateInstance(ITypeDescriptorContext context, IDictionary propertyValues)
{
if (propertyValues != null && propertyValues.Contains("Text"))
return new Bar { Text = (string)propertyValues["Text"] };
return new Bar();
}
}
After compile, I drag the control in a form then I can see the property Bar.Text showed in the properties window, I also can edit the value and it seems be saved.
But nothing is generated in the InitializeComponent method
So if I reopen the designer, the Text field in the properties window become empty.
Please notice the struct hasn't a custom constructor, so I cannot use InstanceDescriptor.
Do I miss any important steps?
You are missing a few method overrides in the type descriptor:
public class BarConverter : ExpandableObjectConverter
{
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == typeof(InstanceDescriptor))
return true;
return base.CanConvertTo(context, destinationType);
}
public override object ConvertTo(ITypeDescriptorContext context,
CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(InstanceDescriptor))
{
ConstructorInfo ci = typeof(Bar).GetConstructor(new Type[] { typeof(string) });
Bar t = (Bar)value;
return new InstanceDescriptor(ci, new object[] { t.Text });
}
return base.ConvertTo(context, culture, value, destinationType);
}
public override object CreateInstance(ITypeDescriptorContext context,
IDictionary propertyValues)
{
if (propertyValues == null)
throw new ArgumentNullException("propertyValues");
object text = propertyValues["Text"];
return new Bar((string)text);
}
public override bool GetCreateInstanceSupported(ITypeDescriptorContext context)
{
return true;
}
}
And add constructor to the struct:
[TypeConverter(typeof(BarConverter))]
public struct Bar
{
public Bar(string text)
{
Text = text;
}
public string Text { get; set; }
}
And this is how the Bar property serializes:
//
// userControl11
//
this.userControl11.Bar = new SampleWinApp.Bar("Something");
And the bar property will be shown like following image in property grid, having Text property editable:
You may also want to provide a better string representation for the struct by overriding its ToString() method of the struct, and also make the property convertible from string in property grid, by overriding CanConvertFrom and ConvertFrom like PointConverter or SizeConverter.

Show single object Properties divided by attributes using custom Objects PropertyDescriptor in PropertyGrid

I have a problem using custom PropertyDescriptor with objects array.
I have a Class with more Properties with a lot of Attribute like Category and Description.
I want to show list of these properties in a PropertyGrid.
I have written a custom PropertyDescriptor like this:
public class CollectionPropertyDescriptor : PropertyDescriptor {
#region Fields
private object[] objs = null;
private int index = -1;
#endregion
#region PropertyDescriptor
public ObjectsCollectionPropertyDescriptor(object[] coll, int idx)
: base("#" + idx.ToString(), null) {
this.objs = coll;
this.index = idx;
}
public override bool CanResetValue(object component) {
return false;
}
public override string DisplayName {
get { return string.Format("Item ", index + 1); }
}
public override Type ComponentType {
get { return this.objs.GetType(); }
}
public override object GetValue(object component) {
return this.objs[index]; // Here
}
public override bool IsReadOnly {
get { return true; }
}
public override Type PropertyType {
get { return this.objs[index].GetType(); }
}
public override void ResetValue(object component) {
return;
}
public override void SetValue(object component, object value) {
return;
}
public override bool ShouldSerializeValue(object component) {
return false;
}
#endregion
}
In PropertyGrid, I see the correct object properties but without order and no Category Attribute division... Why?
I think that the Custom propertyDescriptor does not consider all its Attributes.
How can I show for every object his Properties like in single selection(ex, divided by categories.)?
I think that you must implement and specify a TypeConverter for Category. It should allow you to type in a text that is transformed to a Category and to display a Category as text.
Ok, i have solved my problem, in CollectionPropertyDescriptor you must override method to get TypeConverter for ONLY object that have his converter in collection like this:
public override TypeConverter Converter {
get {
return TypeDescriptor.GetConverter(this.objs[index]);
}
}
Bye All.

PropertyGrid expandable collection

I want to automatically show every IList as expandable in my PropertyGrid (By "expandable", I obviously mean that the items will be shown).
I don't want to use attributes on each list (Once again, I want it to work for EVERY IList)
I tried to achive it by using a custom PropertyDescriptor and an ExpandableObjectConverter. It works, but after I delete items from the list, the PropertyGrid is not being refreshed, still displaying the deleted items.
I tried to use ObservableCollection along with raising OnComponentChanged, and also RefreshProperties attribute, but nothing worked.
This is my code:
public class ExpandableCollectionPropertyDescriptor : PropertyDescriptor
{
private IList _collection;
private readonly int _index = -1;
internal event EventHandler RefreshRequired;
public ExpandableCollectionPropertyDescriptor(IList coll, int idx) : base(GetDisplayName(coll, idx), null)
{
_collection = coll
_index = idx;
}
public override bool SupportsChangeEvents
{
get { return true; }
}
private static string GetDisplayName(IList list, int index)
{
return "[" + index + "] " + CSharpName(list[index].GetType());
}
private static string CSharpName(Type type)
{
var sb = new StringBuilder();
var name = type.Name;
if (!type.IsGenericType)
return name;
sb.Append(name.Substring(0, name.IndexOf('`')));
sb.Append("<");
sb.Append(string.Join(", ", type.GetGenericArguments()
.Select(CSharpName)));
sb.Append(">");
return sb.ToString();
}
public override AttributeCollection Attributes
{
get
{
return new AttributeCollection(null);
}
}
public override bool CanResetValue(object component)
{
return true;
}
public override Type ComponentType
{
get
{
return _collection.GetType();
}
}
public override object GetValue(object component)
{
OnRefreshRequired();
return _collection[_index];
}
public override bool IsReadOnly
{
get { return false; }
}
public override string Name
{
get { return _index.ToString(); }
}
public override Type PropertyType
{
get { return _collection[_index].GetType(); }
}
public override void ResetValue(object component)
{
}
public override bool ShouldSerializeValue(object component)
{
return true;
}
public override void SetValue(object component, object value)
{
_collection[_index] = value;
}
protected virtual void OnRefreshRequired()
{
var handler = RefreshRequired;
if (handler != null) handler(this, EventArgs.Empty);
}
}
.
internal class ExpandableCollectionConverter : ExpandableObjectConverter
{
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destType)
{
if (destType == typeof(string))
{
return "(Collection)";
}
return base.ConvertTo(context, culture, value, destType);
}
public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes)
{
IList collection = value as IList;
PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null);
for (int i = 0; i < collection.Count; i++)
{
ExpandableCollectionPropertyDescriptor pd = new ExpandableCollectionPropertyDescriptor(collection, i);
pd.RefreshRequired += (sender, args) =>
{
var notifyValueGivenParentMethod = context.GetType().GetMethod("NotifyValueGivenParent", BindingFlags.NonPublic | BindingFlags.Instance);
notifyValueGivenParentMethod.Invoke(context, new object[] {context.Instance, 1});
};
pds.Add(pd);
}
// return the property descriptor Collection
return pds;
}
}
And I use it for all ILists with the following line:
TypeDescriptor.AddAttributes(typeof (IList), new TypeConverterAttribute(typeof(ExpandableCollectionConverter)));
Some Clarifications
I want the grid to automatically update when I change the list. Refreshing when another property changes, does not help.
A solution that works, is a solution where:
If you expand the list while it is empty, and then add items, the grid is refreshed with the items expanded
If you add items to the list, expand it, and then remove items (without collapsing), the grid is refreshed with the items expanded, and not throwing ArgumentOutOfRangeException because it is trying to show items that were deleted already
I want this whole thing for a configuration utility. Only the PropertyGrid should change the collections
IMPORTANT EDIT:
I did manage to make the expanded collections update with Reflection, and calling NotifyValueGivenParent method on the context object when the PropertyDescriptor GetValue method is called (when RefreshRequired event is raised):
var notifyValueGivenParentMethod = context.GetType().GetMethod("NotifyValueGivenParent", BindingFlags.NonPublic | BindingFlags.Instance);
notifyValueGivenParentMethod.Invoke(context, new object[] {context.Instance, 1});
It works perfectly, except it causes the event to be raised infinite times, because calling NotifyValueGivenParent causes a reload of the PropertyDescriptor, and therfore, raising the event, and so on.
I tried to solve it by adding a simple flag that will prevent the reloading if it is already reloading, but for some reason NotifyValueGivenParent behaves asynchronously, and therefore the reloading happens after the flag is turned off.
Maybe it is another direction to explore. The only problem is the recursion
There is no need for using ObservableCollection. You can modify your descriptor class as follows:
public class ExpandableCollectionPropertyDescriptor : PropertyDescriptor
{
private IList collection;
private readonly int _index;
public ExpandableCollectionPropertyDescriptor(IList coll, int idx)
: base(GetDisplayName(coll, idx), null)
{
collection = coll;
_index = idx;
}
private static string GetDisplayName(IList list, int index)
{
return "[" + index + "] " + CSharpName(list[index].GetType());
}
private static string CSharpName(Type type)
{
var sb = new StringBuilder();
var name = type.Name;
if (!type.IsGenericType)
return name;
sb.Append(name.Substring(0, name.IndexOf('`')));
sb.Append("<");
sb.Append(string.Join(", ", type.GetGenericArguments()
.Select(CSharpName)));
sb.Append(">");
return sb.ToString();
}
public override bool CanResetValue(object component)
{
return true;
}
public override Type ComponentType
{
get { return this.collection.GetType(); }
}
public override object GetValue(object component)
{
return collection[_index];
}
public override bool IsReadOnly
{
get { return false; }
}
public override string Name
{
get { return _index.ToString(CultureInfo.InvariantCulture); }
}
public override Type PropertyType
{
get { return collection[_index].GetType(); }
}
public override void ResetValue(object component)
{
}
public override bool ShouldSerializeValue(object component)
{
return true;
}
public override void SetValue(object component, object value)
{
collection[_index] = value;
}
}
Instead of the ExpandableCollectionConverter I would derive the CollectionConverter class, so you can still use the ellipsis button to edit the collection in the old way (so you can add/remove items if the collection is not read-only):
public class ListConverter : CollectionConverter
{
public override bool GetPropertiesSupported(ITypeDescriptorContext context)
{
return true;
}
public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes)
{
IList list = value as IList;
if (list == null || list.Count == 0)
return base.GetProperties(context, value, attributes);
var items = new PropertyDescriptorCollection(null);
for (int i = 0; i < list.Count; i++)
{
object item = list[i];
items.Add(new ExpandableCollectionPropertyDescriptor(list, i));
}
return items;
}
}
And I would use this ListConverter on the properties where I want to see expandable list. Of course, you can register the type converter generally as you do in your example, but that overrides everything, which might not be overall intended.
public class MyClass
{
[TypeConverter(typeof(ListConverter))]
public List<int> List { get; set; }
public MyClass()
{
List = new List<int>();
}
[RefreshProperties(RefreshProperties.All)]
[Description("Change this property to regenerate the List")]
public int Count
{
get { return List.Count; }
set { List = Enumerable.Range(1, value).ToList(); }
}
}
Important: The RefreshProperties attribute should be defined for the properties that change other properties. In this example, changing the Count replaces the whole list.
Using it as propertyGrid1.SelectedObject = new MyClass(); produces the following result:
I don't want it to refresh when other property refreshes. I want it to refresh when the list is changed. I add items to the list, expand it, add more items, but the items are not updated
This is a typical misuse of PropertyGrid. It is for configuring a component, and not for reflecting the concurrent changes on-the-fly by an external source. Even wrapping the IList into an ObservableCollection will not help you because it is used only by your descriptor, while the external source manipulates directly the underlying IList instance.
What you can still do is an especially ugly hack:
public class ExpandableCollectionPropertyDescriptor : PropertyDescriptor
{
// Subscribe to this event from the form with the property grid
public static event EventHandler CollectionChanged;
// Tuple elements: The owner of the list, the list, the serialized content of the list
// The reference to the owner is a WeakReference because you cannot tell the
// PropertyDescriptor that you finished the editing and the collection
// should be removed from the list.
// Remark: The references here may survive the property grid's life
private static List<Tuple<WeakReference, IList, byte[]>> collections;
private static Timer timer;
public ExpandableCollectionPropertyDescriptor(ITypeDescriptorContext context, IList collection, ...)
{
AddReference(context.Instance, collection);
// ...
}
private static void AddReference(object owner, IList collection)
{
// TODO:
// - serialize the collection into a byte array (BinaryFormatter) and add it to the collections list
// - if this is the first element, initialize the timer
}
private static void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
// TODO: Cycle through the collections elements
// - If WeakReference is not alive, remove the item from the list
// - Serialize the list again and compare the result to the last serialized content
// - If there a is difference:
// - Update the serialized content
// - Invoke the CollectionChanged event. The sender is the owner (WeakReference.Target).
}
}
Now you can use it like this:
public class Form1 : Form
{
MyObject myObject = new MyObject();
public MyForm()
{
InitializeComponent();
ExpandableCollectionPropertyDescriptor.CollectionChanged += CollectionChanged();
propertyGrid.SelectedObject = myObject;
}
private void CollectionChanged(object sender, EventArgs e)
{
if (sender == myObject)
propertyGrid.SelectedObject = myObject;
}
}
But honestly, I would not use it at all. It has serious flaws:
What if a collection element is changed by the PropertyGrid, but the timer has not updated the last external change yet?
The implementer of the IList must be serializable
Ridiculous performance overhead
Though using weak references may reduce memory leaks, it does not help if the objects to edit have longer life cycle than the editor form, because they will remain in the static collection
Putting it all together, this works:
Here is the class with the lists that we will put an instance of in our property grid. Also to demonstrate usage with a list of a complex object, I have the NameAgePair class.
public class SettingsStructure
{
public SettingsStructure()
{
//To programmatically add this to properties that implement ILIST for the naming of the edited node and child items:
//[TypeConverter(typeof(ListConverter))]
TypeDescriptor.AddAttributes(typeof(IList), new TypeConverterAttribute(typeof(ListConverter)));
//To programmatically add this to properties that implement ILIST for the refresh and expansion of the edited node
//[Editor(typeof(CollectionEditorBase), typeof(System.Drawing.Design.UITypeEditor))]
TypeDescriptor.AddAttributes(typeof(IList), new EditorAttribute(typeof(CollectionEditorBase), typeof(UITypeEditor)));
}
public List<string> ListOfStrings { get; set; } = new List<string>();
public List<string> AnotherListOfStrings { get; set; } = new List<string>();
public List<int> ListOfInts { get; set; } = new List<int>();
public List<NameAgePair> ListOfNameAgePairs { get; set; } = new List<NameAgePair>();
}
public class NameAgePair
{
public string Name { get; set; } = "";
public int Age { get; set; } = 0;
public override string ToString()
{
return $"{Name} ({Age})";
}
}
Here is the ListConverter class to handle making the child nodes.
public class ListConverter : CollectionConverter
{
public override bool GetPropertiesSupported(ITypeDescriptorContext context)
{
return true;
}
public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes)
{
IList list = value as IList;
if (list == null || list.Count == 0)
return base.GetProperties(context, value, attributes);
var items = new PropertyDescriptorCollection(null);
for (int i = 0; i < list.Count; i++)
{
object item = list[i];
items.Add(new ExpandableCollectionPropertyDescriptor(list, i));
}
return items;
}
public override object ConvertTo(ITypeDescriptorContext pContext, CultureInfo pCulture, object value, Type pDestinationType)
{
if (pDestinationType == typeof(string))
{
IList v = value as IList;
int iCount = (v == null) ? 0 : v.Count;
return $"({iCount} Items)";
}
return base.ConvertTo(pContext, pCulture, value, pDestinationType);
}
}
Here is the ExpandableCollectionPropertyDescriptor class for the individual items.
public class ExpandableCollectionPropertyDescriptor : PropertyDescriptor
{
private IList _Collection;
private readonly int _Index;
public ExpandableCollectionPropertyDescriptor(IList coll, int idx) : base(GetDisplayName(coll, idx), null)
{
_Collection = coll;
_Index = idx;
}
private static string GetDisplayName(IList list, int index)
{
return "[" + index + "] " + CSharpName(list[index].GetType());
}
private static string CSharpName(Type type)
{
var sb = new StringBuilder();
var name = type.Name;
if (!type.IsGenericType) return name;
sb.Append(name.Substring(0, name.IndexOf('`')));
sb.Append("<");
sb.Append(string.Join(", ", type.GetGenericArguments().Select(CSharpName)));
sb.Append(">");
return sb.ToString();
}
public override bool CanResetValue(object component)
{
return true;
}
public override Type ComponentType
{
get { return this._Collection.GetType(); }
}
public override object GetValue(object component)
{
return _Collection[_Index];
}
public override bool IsReadOnly
{
get { return false; }
}
public override string Name
{
get { return _Index.ToString(CultureInfo.InvariantCulture); }
}
public override Type PropertyType
{
get { return _Collection[_Index].GetType(); }
}
public override void ResetValue(object component)
{
}
public override bool ShouldSerializeValue(object component)
{
return true;
}
public override void SetValue(object component, object value)
{
_Collection[_Index] = value;
}
}
And then the CollectionEditorBase class for refreshing the property grid after the collection editor is closed.
public class CollectionEditorBase : CollectionEditor
{
protected PropertyGrid _PropertyGrid;
private bool _ExpandedBefore;
private int _CountBefore;
public CollectionEditorBase(Type type) : base(type) { }
public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
{
//Record entry state of property grid item
GridItem giThis = (GridItem)provider;
_ExpandedBefore = giThis.Expanded;
_CountBefore = (giThis.Value as IList).Count;
//Get the grid so later we can refresh it on close of editor
PropertyInfo piOwnerGrid = provider.GetType().GetProperty("OwnerGrid", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
_PropertyGrid = (PropertyGrid)piOwnerGrid.GetValue(provider);
//Edit the collection
return base.EditValue(context, provider, value);
}
protected override CollectionForm CreateCollectionForm()
{
CollectionForm cf = base.CreateCollectionForm();
cf.FormClosing += delegate (object sender, FormClosingEventArgs e)
{
_PropertyGrid.Refresh();
//Because nothing changes which grid item is the selected one, expand as desired
if (_ExpandedBefore || _CountBefore == 0) _PropertyGrid.SelectedGridItem.Expanded = true;
};
return cf;
}
protected override object CreateInstance(Type itemType)
{
//Fixes the "Constructor on type 'System.String' not found." when it is an empty list of strings
if (itemType == typeof(string)) return string.Empty;
else return Activator.CreateInstance(itemType);
}
}
Now the usage produces:
And performing various operations produces:
You can tweak it to operate like you like.

Hide ellipsis (…) button of expandable property like "…" button of font property in the property grid

I've added a new property to my custom control as expandable property like font property in Property Grid. After using from my custom control in a Windows Forms Application project, I see an ellipsis (…) button like "…" button of font property in Property Grid. (For more information, please see the following picture.)
Now, I want to hide the ellipsis (…) button for my new expandable property.
Expandable property codes are:
[DisplayName("Floors Information")]
[Description("Floors Informationnnnnnnnnnnnnnnn")]
[DefaultProperty("TitleText")]
[DesignerCategory("Component")]
public class FloorsInformation : DockContainerItem
{
private SimilarFloorsInformation similarFloorsInformation = new SimilarFloorsInformation();
public FloorsInformation()
{
}
[Category("Data")]
[DisplayName("Similar Floors Panel")]
[Description("Similar Floors Panellllllllllllllllllll")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
[Editor(typeof(ItemsCollectionEditor), typeof(UITypeEditor))]
//[TypeConverter(typeof(ExpandableObjectConverter))]
//[TypeConverter(typeof(SimilarFloorsInformationTypeConverter))]
public SimilarFloorsInformation SimilarFloorsInfo
{
get
{
return similarFloorsInformation;
}
}
}
[DisplayName("Similar Floors Information")]
[Description("Similar Floors Informationnnnnnnnnnnnnnnn")]
[DefaultProperty("Text")]
[DesignerCategory("Component")]
[TypeConverter(typeof(SimilarFloorsInformationTypeConverter))]
//[TypeConverter(typeof(ExpandableObjectConverter))]
public class SimilarFloorsInformation : ExpandablePanel
{
private Color canvasColor = SystemColors.Control;
private eCollapseDirection collapseDirection = eCollapseDirection.LeftToRight;
private eDotNetBarStyle colorSchemeStyle = eDotNetBarStyle.StyleManagerControlled;
private DockStyle dock = DockStyle.Right;
private eTitleButtonAlignment expandButtonAlignment = eTitleButtonAlignment.Left;
private bool expanded = false;
private bool markupUsesStyleAlignment = true;
private Size size = new Size(30, 177);
public SimilarFloorsInformation()
{
}
}
public class SimilarFloorsInformationTypeConverter : ExpandableObjectConverter//TypeConverter
{
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == typeof(SimilarFloorsInformation))
{
return true;
}
return base.CanConvertTo(context, destinationType);
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(String) && value is SimilarFloorsInformation)
{
SimilarFloorsInformation similarFloorsInformation = (SimilarFloorsInformation)value;
return similarFloorsInformation.TitleText;
}
return base.ConvertTo(context, culture, value, destinationType);
}
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof(string))
{
return true;
}
return base.CanConvertFrom(context, sourceType);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
if (value is string)
{
SimilarFloorsInformation similarFloorsInformation = new SimilarFloorsInformation();
similarFloorsInformation.TitleText = (string)value;
return similarFloorsInformation;
}
return base.ConvertFrom(context, culture, value);
}
}
You should implement your own class derived from UITypeEditor and override GetEditStyle method as follows:
public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
{
return UITypeEditorEditStyle.None;
}
Then use EditorAttribute:
[Editor(typeof(YourTypeEditor), typeof(UITypeEditor))]
Update 1:
Well. I just realized you're already applying EditorAttribute on the property:
[Editor(typeof(ItemsCollectionEditor), typeof(UITypeEditor))]
public SimilarFloorsInformation SimilarFloorsInfo
{
get
{
return similarFloorsInformation;
}
}
So you should override GetEditStyle in ItemsCollectionEditor.
I solved my problem according to Nikolay Khil answer. Ellipsis (...) button is shown for following line of code (Attribute) that I've applied to the "SimilarFloorsInfo" property of my custom control:
[Editor(typeof(ItemsCollectionEditor), typeof(UITypeEditor))]
So, this line of code must be deleted or commented. Now, Ellipsis (...) button not shown for my property in the property grid.

C# How to expose a property based on the value of another property in a propertygrid?

I have class with multiple properties. Sometimes a property (A) may be edited in a propertygrid. But sometimes property A may not be edited. This depends on a value of another property.
How can I do this?
EDIT:
I am sorry, I forget to mention that I want this in design-time.
Runtime property models are an advanced topic. For PropertyGrid the easiest route would be to write a TypeConverter, inheriting from ExpandableObjectConverter. Override GetProperties, and swap the property in question for a custom one.
Writing a PropertyDescriptor from scratch is a chore; but in this case you mainly just need to chain ("decorator") all the methods to the original (reflective) descriptor. And just override IsReadOnly to return the bool you want.
By no means trivial, but achievable.
using System;
using System.ComponentModel;
using System.Windows.Forms;
static class Program
{
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.Run(new Form { Text = "read only",
Controls = {
new PropertyGrid { Dock = DockStyle.Fill, SelectedObject = new Foo { IsBarEditable = false }}
}
});
Application.Run(new Form { Text = "read write",
Controls = {
new PropertyGrid { Dock = DockStyle.Fill, SelectedObject = new Foo { IsBarEditable = true }}
}
});
}
}
[TypeConverter(typeof(Foo.FooConverter))]
class Foo
{
[Browsable(false)]
public bool IsBarEditable { get; set; }
public string Bar { get; set; }
private class FooConverter : ExpandableObjectConverter
{
public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes)
{
var props = base.GetProperties(context, value, attributes);
if (!((Foo)value).IsBarEditable)
{ // swap it
PropertyDescriptor[] arr = new PropertyDescriptor[props.Count];
props.CopyTo(arr, 0);
for (int i = 0; i < arr.Length; i++)
{
if (arr[i].Name == "Bar") arr[i] = new ReadOnlyPropertyDescriptor(arr[i]);
}
props = new PropertyDescriptorCollection(arr);
}
return props;
}
}
}
class ReadOnlyPropertyDescriptor : ChainedPropertyDescriptor
{
public ReadOnlyPropertyDescriptor(PropertyDescriptor tail) : base(tail) { }
public override bool IsReadOnly
{
get
{
return true;
}
}
public override void SetValue(object component, object value)
{
throw new InvalidOperationException();
}
}
abstract class ChainedPropertyDescriptor : PropertyDescriptor
{
private readonly PropertyDescriptor tail;
protected PropertyDescriptor Tail { get {return tail; } }
public ChainedPropertyDescriptor(PropertyDescriptor tail) : base(tail)
{
if (tail == null) throw new ArgumentNullException("tail");
this.tail = tail;
}
public override void AddValueChanged(object component, System.EventHandler handler)
{
tail.AddValueChanged(component, handler);
}
public override AttributeCollection Attributes
{
get
{
return tail.Attributes;
}
}
public override bool CanResetValue(object component)
{
return tail.CanResetValue(component);
}
public override string Category
{
get
{
return tail.Category;
}
}
public override Type ComponentType
{
get { return tail.ComponentType; }
}
public override TypeConverter Converter
{
get
{
return tail.Converter;
}
}
public override string Description
{
get
{
return tail.Description;
}
}
public override bool DesignTimeOnly
{
get
{
return tail.DesignTimeOnly;
}
}
public override string DisplayName
{
get
{
return tail.DisplayName;
}
}
public override PropertyDescriptorCollection GetChildProperties(object instance, Attribute[] filter)
{
return tail.GetChildProperties(instance, filter);
}
public override object GetEditor(Type editorBaseType)
{
return tail.GetEditor(editorBaseType);
}
public override object GetValue(object component)
{
return tail.GetValue(component);
}
public override bool IsBrowsable
{
get
{
return tail.IsBrowsable;
}
}
public override bool IsLocalizable
{
get
{
return tail.IsLocalizable;
}
}
public override bool IsReadOnly
{
get { return tail.IsReadOnly; }
}
public override string Name
{
get
{
return tail.Name;
}
}
public override Type PropertyType
{
get { return tail.PropertyType; }
}
public override void RemoveValueChanged(object component, EventHandler handler)
{
tail.RemoveValueChanged(component, handler);
}
public override void ResetValue(object component)
{
tail.ResetValue(component);
}
public override void SetValue(object component, object value)
{
tail.SetValue(component, value);
}
public override bool ShouldSerializeValue(object component)
{
return tail.ShouldSerializeValue(component);
}
public override bool SupportsChangeEvents
{
get
{
return tail.SupportsChangeEvents;
}
}
}
This answer assumes you are talking about WinForms. If you would like to change one property's readonly state based on another, you will need to have your object implement ICustomTypeDescriptor. This isn't a simple thing to do, but it will give you lots of flexibility about how your class is displayed in the propertygrid.
I've offered a similar solution in the past via this stack solution. It makes use of a custom property, and conditionally ignores an attempt to change at design-time vs run-time, but I'm sure could be altered in the SETter by applying your own "criteria" to allow it being changed...

Categories