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

이보십시오.

편집

마우스 아웃 Mouse Out

+0

가 아니,이 작동하지 않습니다 MouseOver

마우스를 입력합니다. 버튼은 IsMouseOver 종속성 속성 트리거로 변경된 직후 MouseEnter 이벤트 처리기에서 설정된 배경을 덮어 쓰게됩니다. 이는 배경을 기본 크롬으로 설정합니다. 스타일 트리거 또는 이와 비슷한 것이 여기에 필요합니다. –

+0

안녕하세요 마이클, 실제로 동일한 그라디언트 값으로 테스트하여 제대로 작동하는 것으로 나타났습니다 (답변에 첨부 된 화면 캡처). 스타일/배경 값을 다른 위치로 재설정하지 않습니까? –

+0

Vista 또는 Windows 7에서 Aero를 사용하여이 기능을 사용하고 있습니까? Aero가 활성화 된 Windows 7을 사용하고 있습니다. –