2010-12-12 56 views
1

我有以下代碼,以動態創建並添加一個按鈕面板:改變動態創建按鈕的背景在WPF

StackPanel topPanel=...; 
Button button=new Button(); 

button.Content="New Button "+topPanel.Children.Count;  

// Set button background to a red/yellow linear gradient 
// Create a default background brush 
var bgBrush=new LinearGradientBrush(new GradientStopCollection(
    new GradientStop[] {new GradientStop(Color.FromRgb(255,255,200),0.5), 
         new GradientStop(Color.FromRgb(255,200,200),0.5)})); 
// Create a more intense mouse over background brush 
var bgMouseOverBrush=new LinearGradientBrush(new GradientStopCollection(
    new GradientStop[] {new GradientStop(Color.FromRgb(255,255,100),0.5), 
         new GradientStop(Color.FromRgb(255,100,100),0.5)})); 

// Set the button's background 
button.Background=bgBrush; 
// Dynamically, add the button to the panel 
topPanel.Children.Add(button); 

的問題是,當我將鼠標光標移動到按鈕上,它會恢復到其之前的淺藍色背景。現在,我已經讀過,我需要的是一個鼠標懸停按鈕觸發器,但我不知道如何以編程方式爲此按鈕單獨執行此操作。基本上,當鼠標光標移到它後面時,我希望它的背景更改爲bgMouseOverBrush,當它不是時,它的背景更改爲bgBrush

回答

2

試試這個:

// In the constructor or any approp place 
    button.MouseEnter += new MouseEventHandler(b_MouseEnter); 
    button.MouseLeave += new MouseEventHandler(b_MouseLeave); 

    void b_MouseLeave(object sender, MouseEventArgs e) 
    { 
     button.Background=bgBrush; 
    } 

    void b_MouseEnter(object sender, MouseEventArgs e) 
    { 
     button.Background = bgMouseOverBrush; 
    } 

希望有所幫助。

編輯

鼠標進入 MouseOver

鼠標移出 Mouse Out

+0

不,這是行不通的。很明顯,按鈕會在使用IsMouseOver依賴屬性觸發器更改後重設MouseEnter事件處理器中設置的背景,後者將背景設置爲默認鑲邊。風格觸發器或類似的東西在這裏需要。 – 2010-12-12 19:59:22

+0

嗨邁克爾,我實際上測試了相同的梯度值,發現它工作得很好(屏幕捕獲附加到答案)。你確定你沒有重置其他地方的風格/背景值嗎? – 2010-12-12 20:18:10

+0

您是否在Vista或Windows 7上啓用了Aero並嘗試這種方式?我正在使用啓用了Aero的Windows 7 – 2010-12-12 20:51:02