Search code examples
wpfvisual-studio-2015blend

How to change the Brush color from a Pen in a DrawingGroup.Children tag


I'm trying to change the property Brush from the next piece of code from another control, but don't know how to reach to this property.

This drawing brush is defined as an Application.Resource en App.XAML

<DrawingBrush x:Key="Disp_Origin" Stretch="Uniform">
        <DrawingBrush.Drawing>
            <DrawingGroup>
                <DrawingGroup.Children>
                    <GeometryDrawing Geometry="F1 M 720.099,497.862C 778.822,493.976 837.662,492.02 896.514,492.02">
                        <GeometryDrawing.Pen>
                            <Pen Thickness="1.33333" MiterLimit="2.75" Brush="#FFA5AEB7"/>
                        </GeometryDrawing.Pen>
                    </GeometryDrawing>...

I need to reach the pen brush property when another control gets focused or hovered.

I don't know if this is possible


Solution

  • Actually I've found how to do this. But it requires code behind. Most important is Clone() method it allows to change control's resource and you should set this brush resource from code behind. And unfortunately code is not good readable.

    // Initializing code
    // And as mentioned in comments code for restore color
    DrawingBrush myBrush = ( Application.Current.Resources["Disp_Origin"] as DrawingBrush ).Clone();
    testButton.Background = myBrush;
    
    // On hover or on focus code
    DrawingBrush settedBrush = testButton.Background as DrawingBrush;
    ( ( System.Windows.Media.GeometryDrawing )( ( ( System.Windows.Media.DrawingGroup )
       ( settedBrush.Drawing ) ).Children[0] ) ).Pen.Brush = new SolidColorBrush( Colors.Red );
    

    Update

    As mentioned in comments, it needed to restore brush when the control is not focused or covered.