Silverlight Tiled Image Brush

HTML has repeat-x and repeat-y for years but Silverlight hasn’t managed to catch up. It’s elder sibling, WPF, has an ImageBrush which supports TileMode such as Tile, FlipX, FlipXY, FlipY.

This is rather handy if you want textured UI which is now common through out the web.

<!-- wpf only, this is not supported in Silverlight -->
<ListBox>
  <ListBox.Background>
     <ImageBrush ImageSource="grey_wash_wall.png" 
        TileMode="Tile" 
        Stretch="None" 
        ViewportUnits="Absolute" 
         Viewport="0,0,350,259"/>
      </ListBox.Background>
</ListBox>        

With a bit of help from existing code on pixel shaders (see references below), I managed to hone the code down to something that looks like the following:

<!-- wpf only, this is not supported in Silverlight -->
<ListBox Tile:Tile.Mode="Tile">
  <ListBox.Background>
     <ImageBrush ImageSource="grey_wash_wall.png" />
  </ListBox.Background>
</ListBox>        

There are a lot of assumptions going here. The attached property Tile:Mode walks down the visual tree and finds an element which has the background set to the same background as specified on the control. Since the ImageBrush doesn’t tile, we insert an Image into the visual tree. This image has a Tiled ShaderEffect attached and voila! Faked TiledImageBrush.

Caveats

If your template binds the Background to a Rectangle, this can be problematic as the the pixel shader will not clip properly.

Source

You can grab the code at https://github.com/teyc/SilverlightTiledImageBrush.

References

http://silverscratch.blogspot.com.au/2010/09/tiled-image-brush-for-silverlight.html