How can a brush which is used for the BackgroundProperty of a WPF control be given a margin?

StackOverflow https://stackoverflow.com/questions/13695051

  •  04-12-2021
  •  | 
  •  

Question

In WPF, I have a TextBox with a BackgroundProperty set to a custom brush. I want to give this brush some kind of visual buffer from the border of the TextBox. The brush is a GlyphRunBrush which acts much like an ImageBrush, but has a rasterized glyph run as the brush source.

How can I do this?

Example: enter image description here

Was it helpful?

Solution

One way would be to apply a transformation to the brush itself, like so:

<TextBox>
    <TextBox.Background>
        <ImageBrush ImageSource="/MyApp;component/Search.ico"
                    AlignmentX="Right" Stretch="Uniform">
            <ImageBrush.Transform>
                <TransformGroup>
                    <TranslateTransform X="-5"/>
                </TransformGroup>
            </ImageBrush.Transform>
        </ImageBrush>
    </TextBox.Background>
</TextBox>

You could also try changing the width on the brush's Viewport property, but since you're aligning it on the right side, that may be more complicated than it needs to be.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top