Add Elements to Microsoft WinForm Control
Could you tell me if it is possible to add an element to a Microsoft WinForms control?
For example: Suppose you have an application that has several users, each of which have their own "permissions," which are represented simply by the strings "1," "2," "3," etc. You also have several buttons on your application, which should be enabled/disabled according to the permission level of the current user.
Would it be possible to add a "String" to the "Button" control, which could indicate what permission level this button represents.
The reason this is helpful, is because I could loop through all of my buttons and disable them if the current开发者_运维问答 user's permission level is not high enough.
I hope this makes sense.
Thanks.
There is a Tag
property on WinForms controls that you can use to store a reference to related information. It is of type object
, so it can store anything. (msdn reference)
myButton.Tag = "1";
If you want to store more than one thing, then create a class for it:
class UserTag
{
public string Permission {get;set;}
public string Name {get;set;}
}
....
myButton.Tag = new UserTag { Permission="1", Name="Alice" };
....
// Use like this: ((UserTag)myButton.Tag).Permission
Maintain and storing logics behind UI is not an appropriate solution, It makes things harder as your projects grows larger, Store your logics in data structures and make UI compatible and suitable by using the datas.
anyway the solution to your problem is both IExtenderProvider
said by Hans and Matt's Answer.
----EDIT----
//this is just a simple sample! :D
Dictionary<string, int[]> CtrlType = new Dictionary<string, int[]>();
CtrlType.Add(button1.Name, new int[] { 2, 3 });
//add another controls status or attributes for user customizing
//.
//.
//.
//somewhere in your form UI Customization for users
button1.Enabled = CtrlType[button1.Name].Contains(UserID) ? true : false;
//handle another controls attributes
精彩评论