So I have a main form with 3 controls whose Enable
property I want to control using an enum.
All these controls have a reference to the Data
that contains the Enum
value Level.
enum Level
{
Red,
Yellow,
Green
}
So if it's Red
, I want the RedC开发者_运维百科ontrol
to become enabled, if it's yellow
, then YellowControl
becomes enabled, etc.
How do I best do this with minimal code and elegance?
I tried having 3 properties like IsRed
, IsYellow
, etc on the Data
to hook them up. But then I didn't know a way to detect the change of Level
from those properties.
[Flags]
enum Level:int
{
Red = 1,
Green = 2,
Blue = 4,
Yellow = Red | Green,
White = Red | Green | Blue
}
public class myControl : WebControl
{
public Level color;
...
}
public static class extension
{
public static bool Compare(this Level source, Level comparer)
{
return (source & comparer) > 0; // will check RGB base color
//return (source & comparer) == source; // will check for exact color
}
}
usage
var color = Level.Red;
bool result = color.Compare(Level.Green);
myControl test = new myControl();
test.Enabled = test.Color.Compare(Level.Red);
Im not sure about databinding it... but what about putting enabling code in the property' s set?
ie
public YourClass
{
Level _level;
public Level level
{
get{ return _level;}
set
{
_level = value;
if(_level == Level.Green) { greenControl.Enable = true; //plus disable others }
if(_level == Level.Yellow) { yellowControl.Enable = true; //plus disable others }
if(_level == Level.Red) { redControl.Enable = true; //plus disable others }
}
}
}
that way your property works like normal (and I guess you can databind it but im not really sure) and when it gets changed the controllers will change.
RedControl.Enabled = ((value & Level.Red) != 0)
Your binding source class could implement the System.ComponentModel.INotifyPropertyChanged
. I think it's a flexible way to do databinding in windows forms.
Here's one article on codeproject showing how to do it. I've haven't analysed it very deeply, though.
精彩评论