Hi is there a way to change propertys attribute from the code?
Let´s say that i have the following property in my class:
[DisplayName("Nu mber of cars")]
public int Count[
get { . . . }
set { . . . ]
}
Is there a way to change the displayname, from my code, at runtime to
"Number of bikes".
thx!
Kimmo Laine 5 57910
Yes; kind of... but not trivial... I guess it comes down to "why?" as to
whether it is worth the effort... are you using this on a property grid or
something? Because if this is just for a column heading on a grid, I suspect
you can override that text on the grid control...
You could try just obtaining the reflective attribute via GetType and
GetProperty, but IIRC this doesn't "stick".
However, for the /component/ model (which Forms binding uses) you can
actually do pretty much anything... invent properties on the fly, rename
them, change the attributes, etc:
You can implement the ICustomTypeDesc riptor interface; forward most of the
methods to the TypeDescriptor equivalents (using GetType(), not "this" as
the parameter); for GetProperties, call the TypeDescriptor version, but then
change the results for the property you care about... instead of returning
the (reflective) PropertyDescrip tor you get, you should be able to return a
bespoke one that changes the Attributes.
Too much there for a short example, but I have useed the above (as part of a
complex system) with great success (for dynamic properties similar to
DataSet columnns).
Marc
Try this may require a little tweaking but should be close:
using System;
using System.Reflecti on;
// A custom attribute to allow a target to have a display value.
public class DisplayName: Attribute {
// The constructor is called when the attribute is set.
public AnimalTypeAttri bute(String Value) {
_value = Value;
}
// Keep a variable internally ...
protected string _value;
// .. and show a copy to the outside world.
public string Value {
get { return _value; }
set { _value = value; }
}
}
// A test class where property has its own display value.
class DisplayNameTest Class {
[DisplayName("Nu mber of cars")]
public int Count
{
get { . . . }
set { . . . }
}
}
class DemoClass {
static void Main(string[] args) {
DisplayNameTest Class testClass = new DisplayNameTest Class
Type type = testClass.GetTy pe();
FieldInfo myFieldInfo = type.GetField(" Count")
DisplayName att =
(DisplayName)At tribute.GetCust omAttribute(myF ieldInfo,Type.G etType("Display Name"));
att.Value = "Number of bikes";
}
}
"Kimmo Laine" wrote:
Hi is there a way to change propertys attribute from the code?
Let´s say that i have the following property in my class:
[DisplayName("Nu mber of cars")]
public int Count[
get { . . . }
set { . . . ]
}
Is there a way to change the displayname, from my code, at runtime to
"Number of bikes".
thx!
Kimmo Laine
Well, to my mind, the main use of the [DisplayName] is for the component
model - otherwise the OP could just use a static property of
"CountDisplayNa me" or similar and read it at runtime.
For this to be useful, it would have to return the correct value to the
following (which is what 99% of callers will be using):
string displayName = // wrap
TypeDescriptor. GetProperties(t estClass)["Count"].DisplayName;
The code posted won't satisfy this, since the component model will simply
ignore the new "DisplayNam e" attribute, using the pucka DisplayNameAttr ibute
from the System.Componen tModel namespace instead.
Additionally, the DisplayNameAttr ibute.DisplayNa me property is readonly, so
you can't tweak it with reflection. In short, I don't think this will behave
as expected.
Marc
OK, here's the full version; obviously you can change other discreet
values via the PropertyDescrip tor implementation, or any attribute via
GetAttributes. I have implemented it as a static instance here, but you
could merrily recreate for each instance, or even on each call.
Personally I use an extenstion of this in a dynamic property bag
approach.
Most of the code is boiler-plate; ForwardingPrope rtyDescriptor just
allows a daisy-chain. I've chucked in a demo to illustrate it working
with a property-grid and data-grid-view.
using System;
using System.Componen tModel;
using System.Collecti ons.Generic;
using System.Windows. Forms;
class Program {
static void Main() {
SomeClass test = new SomeClass();
ShowObject(test , "Before");
SomeClass.Count DisplayName = "Toadstool count";
ShowObject(test , "After");
}
private static void ShowObject(Some Class item, string title) {
using (Form form = new Form())
using (PropertyGrid propGrid = new PropertyGrid())
using (DataGridView gridView = new DataGridView()) {
form.Height = 500;
form.Text = title;
propGrid.Dock = DockStyle.Fill;
gridView.Dock = DockStyle.Botto m;
form.Controls.A dd(propGrid);
form.Controls.A dd(gridView);
propGrid.Select edObject = item;
List<SomeClassi tems = new List<SomeClass> ();
items.Add(item) ;
gridView.DataSo urce = items;
form.ShowDialog ();
}
}
}
class SomeClass : ICustomTypeDesc riptor {
private int count = 5;
[DisplayName("Co unt of something"), DefaultValue(5)]
public int Count {
get {return count;}
set {count = value;}
}
private string somethingElse = "Empty";
[DisplayName("An other Property"), DefaultValue("E mpty")]
public string SomethingElse {
get { return somethingElse; }
set { somethingElse = value; }
}
AttributeCollec tion ICustomTypeDesc riptor.GetAttri butes() {
return TypeDescriptor. GetAttributes(G etType());
}
string ICustomTypeDesc riptor.GetClass Name() {
return TypeDescriptor. GetClassName(Ge tType());
}
string ICustomTypeDesc riptor.GetCompo nentName() {
return TypeDescriptor. GetComponentNam e(GetType());
}
TypeConverter ICustomTypeDesc riptor.GetConve rter() {
return TypeDescriptor. GetConverter(Ge tType());
}
EventDescriptor ICustomTypeDesc riptor.GetDefau ltEvent() {
return TypeDescriptor. GetDefaultEvent (GetType());
}
PropertyDescrip tor ICustomTypeDesc riptor.GetDefau ltProperty() {
return TypeDescriptor. GetDefaultPrope rty(GetType());
}
object ICustomTypeDesc riptor.GetEdito r(Type editorBaseType) {
return TypeDescriptor. GetEditor(GetTy pe(), editorBaseType) ;
}
EventDescriptor Collection
ICustomTypeDesc riptor.GetEvent s(Attribute[] attributes) {
return TypeDescriptor. GetEvents(GetTy pe(), attributes);
}
EventDescriptor Collection ICustomTypeDesc riptor.GetEvent s() {
return TypeDescriptor. GetEvents(GetTy pe());
}
PropertyDescrip torCollection
ICustomTypeDesc riptor.GetPrope rties(Attribute[] attributes) {
return HackProperties( TypeDescriptor. GetProperties(G etType(),
attributes));
}
PropertyDescrip torCollection ICustomTypeDesc riptor.GetPrope rties()
{
return HackProperties( TypeDescriptor. GetProperties(G etType()));
}
object ICustomTypeDesc riptor.GetPrope rtyOwner(Proper tyDescriptor
pd) {
return this;
}
private PropertyDescrip torCollection
HackProperties( PropertyDescrip torCollection properties) {
List<PropertyDe scriptorpropLis t = new
List<PropertyDe scriptor>();
foreach (PropertyDescri ptor prop in properties) {
if (prop.Name == "Count")
propList.Add(Co untPropertyDesc riptor);
else
propList.Add(pr op);
}
return new PropertyDescrip torCollection(p ropList.ToArray (),
true);
}
private static readonly DisplayNameProp ertyDescriptor
CountPropertyDe scriptor;
public SomeClass() { }
public static string CountDisplayNam e {
get { return CountPropertyDe scriptor.Displa yName; }
set { CountPropertyDe scriptor.SetDis playName(value) ; }
}
static SomeClass() {
CountPropertyDe scriptor = new
DisplayNameProp ertyDescriptor( TypeDescriptor. GetProperties(t ypeof(SomeClass ))["Count"]);
}
}
public class DisplayNameProp ertyDescriptor :
ForwardingPrope rtyDescriptor {
private string displayName;
public void SetDisplayName( string displayName) {
this.displayNam e = displayName;
}
public DisplayNameProp ertyDescriptor( PropertyDescrip tor root)
: base(root) {
SetDisplayName( root.DisplayNam e);
}
public override string DisplayName {
get { return displayName; }
}
}
public abstract class ForwardingPrope rtyDescriptor : PropertyDescrip tor
{
private readonly PropertyDescrip tor _root;
protected PropertyDescrip tor Root { get { return _root; } }
protected ForwardingPrope rtyDescriptor(P ropertyDescript or root)
: base(root) {
_root = root;
}
public override void AddValueChanged (object component, EventHandler
handler) {
Root.AddValueCh anged(component , handler);
}
public override AttributeCollec tion Attributes {
get {
return Root.Attributes ;
}
}
public override bool CanResetValue(o bject component) {
return Root.CanResetVa lue(component);
}
public override string Category {
get {
return Root.Category;
}
}
public override Type ComponentType {
get { return Root.ComponentT ype; }
}
public override TypeConverter Converter {
get {
return Root.Converter;
}
}
public override string Description {
get {
return Root.Descriptio n;
}
}
public override bool DesignTimeOnly {
get {
return Root.DesignTime Only;
}
}
public override string DisplayName {
get {
return Root.DisplayNam e;
}
}
public override bool Equals(object obj) {
return Root.Equals(obj );
}
public override PropertyDescrip torCollection
GetChildPropert ies(object instance, Attribute[] filter) {
return Root.GetChildPr operties(instan ce, filter);
}
public override object GetEditor(Type editorBaseType) {
return Root.GetEditor( editorBaseType) ;
}
public override int GetHashCode() {
return Root.GetHashCod e();
}
public override object GetValue(object component) {
return Root.GetValue(c omponent);
}
public override bool IsBrowsable {
get {
return Root.IsBrowsabl e;
}
}
public override bool IsLocalizable {
get {
return Root.IsLocaliza ble;
}
}
public override bool IsReadOnly {
get { return Root.IsReadOnly ; }
}
public override string Name {
get {
return Root.Name;
}
}
public override Type PropertyType {
get { return Root.PropertyTy pe; }
}
public override void RemoveValueChan ged(object component,
EventHandler handler) {
Root.RemoveValu eChanged(compon ent, handler);
}
public override void ResetValue(obje ct component) {
Root.ResetValue (component);
}
public override void SetValue(object component, object value) {
Root.SetValue(c omponent, value);
}
public override bool ShouldSerialize Value(object component) {
return Root.ShouldSeri alizeValue(comp onent);
}
public override bool SupportsChangeE vents {
get {
return Root.SupportsCh angeEvents;
}
}
public override string ToString() {
return Root.ToString() ;
}
}
Thx for your replys! I used the Marc´s method and did the following:
// Data which is shown in the propertygrid. It inherits from my custom
descriptor
class MyData : MyCustomDescrip tor {
// Property which i need to localize. Custom attribute holds the string
ID which is loaded from the resource file
[MyAttribute(123 )]
public int Count{ . . . }
}
// Custom descriptor. Used when propertygrid is inspecting my class - MyData
class MyCustomDescrip tor : ICustomTypeDesc riptor {
public PropertyDescrip torCollection GetProperties() {
PropertyDescrip torCollection orgPdc =
TypeDescriptor. GetProperties(t his, true);
PropertyDescrip torCollection newPdc = new
PropertyDescrip torCollection(n ull);
foreach(Propert yDescriptor t in orgPdc) {
// See if the property name needs to be changed
MyAttribute ma = (MyAttribute)t. Attributes[typeof(MyAttrib ute)];
if (ma != null) {
// Create custom description object - explained later
newPdc.Add(new MyDescription(t , ma.MsgID));
} else {
// Use normal
newPdc.Add(t);
}
}
return newPdc;
}
}
// Custom description object - the actual work is done here
class MyDescription : PropertyDescrip tor {
private PropertyDescrip tor m_PD = null;
private int m_MsgID = 0;
public MyDescription(P ropertyDescript or pd, int msgID) : base(pd)
{
m_PD = pd;
m_MsgID = msgID;
}
public override string DisplayName {
get {
return // Load the resource (m_MsgID) from somewhere
}
}
}
-K This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Tom Rahav |
last post by:
Hello.
I use visual basic .net 2003 and Crystal Reports for creating win-reports.
My question is if there is any possibility to set font properties (type,
color and size) of a text control or data field during runtime.
To be more accurate, I know I can set these settings by formula (next to
each property in design time), but I would like to let the user choose what
font settings he would like to use. I allow the user to set there...
|
by: Hans Bampel |
last post by:
Hello group,
i want to overwrite or manipulate a attribute of a property in a
derived class. I use a attribute DBInfo via reflection on my
properties to set the parameters in a SQL-statement dynamically. Now
in a derived class (similar table in the DB), the name of the column a
other one.
what i have
|
by: Luis Arvayo |
last post by:
Is there some way to attach an editor to a property of a class at runtime ?
Ex.;
public class MyClass
{
public int BitmapIndex
|
by: O.A.Haugum |
last post by:
Hi
I want to use a lot of icons in panels in a status bar. The icons shall show
the current status of operations and has to be changed programmatically.
Is it possible to store the icons in the application in the same way as you
store images in an image list? I prefer not get the icons from files.
|
by: Jason Richmeier |
last post by:
Perhaps it is because it is the end of the day and my eyes are tired of
looking at code but I cannot seem to figure out what I am doing wrong and
what I can do (if anything) to fix it.
On a Windows form, I have a ToolStripComboBox object with a handful of
entries in the Items collection. I would like to change the text of the
ToolStripComboBox object (using the Text property) to something other than
the text of one of the items in the...
| |
by: tfsimes |
last post by:
Hi, I am a long time ASP developer learning .NET, so please bear with
me. I am trying to find an article or such that will help me understand
how to change control properties at runtime based on the value in a
field.
For instance, if I want to add some text to a field in a GridView based
on a boolean value in an un-shown field being returned.
Another example would be if I want to bind a Listbox to a table of
people, however I want to...
|
by: Ray Cassick |
last post by:
I am looking for a way to hide a property I created on a user control from a
property grid at runtime but allow it to be seen at design time.
Any ideas?
I tried setting the category of the property to 'Design' and that does not
do it.
I tried adding the 'DesignOnly' attribute and that does not do it.
|
by: Radu |
last post by:
Hi, I have a "select" control named "cboSelectScorecardType", defined
as
<select id="cboSelectScorecardType"
size="1"
runat="server">
</select>
which shows a list of files on my drive. It does not post back, nor do
I want it to. After the user selects a document in the combo, I want a
|
by: Nathan Sokalski |
last post by:
I am attempting to add Attributes to my ASP.NET Controls & Properties. Here
is what my Controls look like:
<ToolboxData("<{0}:Parameter runat=""server""/>")_
Public Class Parameter : Inherits System.Web.UI.Control
Private _name As String
<Description("My Property Description")_
Public WriteOnly Property Name() As String
Set(ByVal value As String)
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
| |
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |