Note: This idea, or solution is suitable for simple, single interface applications that don't require a lot of buttons. If you are working on a Dashboard or LOB application, there are probably many buttons on many pages, and you want to keep the source codes to a minimum, then you should use the Styling Resources technique.
I have replaced my usual <Button /> element with a <Border /> element:
If you enlarge the image by clicking on it, you will see what the Border and StackPanel, TextBlock elements will look like. The StackPanel has been included there so that I can use it for my next tutorial about creating buttons with both text and images. I want to bring your attention to 2 important sections of the XAML coding here that provides the Gradient effects, as well as the events that trigger the MouseEnter and MouseLeave effects:
- MouseLeftButtonDown - This is to simulate the Mouse Click event when the mouse is over the Border element.
- MouseEnter - This is to simulate the MouseOver effect.
- MouseLeave - When the mouse cursor is out of the Border, the default gradient design will be restored.
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FF082CD1" Offset="0"/>
<GradientStop Color="#FF0AB6DC" Offset="1"/>
If you can see above, the LinearGradientBrush has 2 attributes: StartPoint and EndPoint. This are crucial to the LinearGradientBrush, to know where the gradient starting point and ending point is. "0.5, 0" - 0.5 means the center, and 0 means top.
Next, we will take a look at how to render the MouseEnter effect via the codes:
If you see the coding screen shot above.
1. This is where we declare a new LinearGradientBrush object, and we define the same StartPoint and EndPoint as the default design.
2a) Then we continue to define the first GradientStop object and give the color green to it.
2b) We define the next color and and add the gradient stop to the LinearGradientBrush object.
3) The final step is to set the Background of the button to the LinearGradientBrush.
If you enlarge the coding screenshot above, it is exactly the same as the MouseEnter event. The only difference is the Argb values, setting the colors back to the default state.
And that covers how easy it is to create a custom gradient mouse over effect for Silverlight 4/5.