2010-01-08 66 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顯示文章如何做到這一點。不過,我還沒有深入分析過。

相關問題