Search code examples
wpfdata-bindingblendmouse-position

How do I data bind the X/Y coordinates of a radial gradient to the X/Y coordinates of the mouse cursor in Blend?


I'm following this tutorial for how to create a Windows Vista/7 styled glass button in VS Blend (I'm using VS 2013 Community Edition). When it comes to the button shine, I want to re-create how Windows 7 handles buttons on the task bar - as in, when the mouse is over the button, the radial gradient that makes up the shine itself is always centered on the cursor.

My guess to make this work is that I would want to bind the position of the gradient (x and y) to the cursor coordinates.

How, in Blend, do I data-bind the coordinates of a radial gradient to the x/y coordinates of the mouse cursor?


Solution

  • One way is to add a dependency property to the view, and hook that to the MouseMove event.

    The dependency property:

        public static readonly DependencyProperty MousePointProperty = DependencyProperty.Register(
            "MousePoint",
            typeof (Point),
            typeof (MyWindow),
            new FrameworkPropertyMetadata(new Point());
    
        public Point MousePoint
        {
            get { return (Point)GetValue(MousePointProperty ); }
            set { SetValue(MousePointProperty , value); }
        }
    

    Then in the MouseMove handler, update this point. In the XAML (this is on a rectangle, should be similar for your control):

    <Rectangle>
        <Rectangle.Fill>
            <RadialGradientBrush GradientOrigin="{Binding MousePoint}"/>
        </Rectangle.Fill>
    </Rectangle>