2010-01-08 63 views
0

所以我有一个3控件的主窗体,其Enable属性我想控制使用枚举。如何将Enum值绑定到布尔值?

所有这些控件都对Data的引用包含Enum值的级别。

enum Level 
{ 
    Red, 
    Yellow, 
    Green 
} 

所以,如果它是Red,我希望RedControl变成启用,如果它是yellow,然后YellowControl变为启用等

我最好如何用最少的代码和优雅做到这一点?

我试图具有像IsRedIsYellow等上Data 3种性质钩起来。但后来我不知道从这些属性中检测出Level的变化。

回答

1
[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 
} 
} 

使用

var color = Level.Red; 
bool result = color.Compare(Level.Green); 

myControl test = new myControl(); 
test.Enabled = test.Color.Compare(Level.Red); 
0

RedControl.Enabled = ((value & Level.Red) != 0)

+1

这不使用数据绑定工作,并不会编译[(值Level.Red)将返回一个int,而不是一个布尔] – 2010-01-08 19:16:17

+0

感谢名单芦苇 - 坏语法 - 我更正了我的文章 – Ray 2010-01-08 19:23:51

0

林不知道有关数据绑定...但关于把实现代码属性的设置是什么?

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 } 
     } 
    } 
} 

这样你的财产的工作原理是正常的(我想你可以进行数据绑定,但即时通讯真的不知道),当它被改变的控制器将改变。

+0

谢谢,但所有这些控件实例都包含对数据的引用,并且数据中的任何更改都应该适当地提醒所有人。 – 2010-01-08 19:18:23

+0

那么关于当数据变化,然后在每个控件的事件处理程序有控制禁用本身如果不是他喜欢的数据,并启用它本身就是它需要上升的事件。 – 2010-01-08 19:20:53

0

您的绑定来源类可以实施System.ComponentModel.INotifyPropertyChanged。我认为这是一种在Windows窗体中进行数据绑定的灵活方式。

这里有一个codeproject显示文章如何做到这一点。不过,我还没有深入分析过。

相关问题