2010-12-12 10 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に戻してください。助け

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

希望:

答えて

2

はこれを試してみてください。

EDIT

マウスアウト Mouse Out

+0

はいや、これは動作しません MouseOver

マウスを入力します。ボタンは、背景をデフォルトのクロムに設定するIsMouseOver依存プロパティトリガで変更された直後に、MouseEnterイベントハンドラで設定されたバックグラウンドをオーバーライドしているようです。ここではスタイルトリガーなどが必要です。 –

+0

こんにちはマイケル、私は実際に同じ勾配の値をテストし、それがちょうど良い(スクリーンキャプチャは答えに添付されている)ことがわかった。スタイル/バックグラウンドの値を別の場所にリセットしていませんか? –

+0

VistaやWindows 7でAeroが有効になっていますか?私はWindows 7のAeroを有効にしています –

関連する問題