Search code examples
windows-phone-7xaml

How can i set the background of a grid?


Im playing around with styles, and want to set the background of the Grid, something like this:

        <Style TargetType="Grid">
            <Setter Property="Background" Value="Background.png" />
        </Style>

But this does not work, what is the correct way... and how could I do it like I do it with classes in css as I want it to affect every Grid, the one the wraps the page?


Solution

  • You can set the background property directly like so.

    <Grid x:Name="ContentPanel" Style="{StaticResource GridStyle1}">
            <Grid.Background>
                <ImageBrush Stretch="Fill" ImageSource="/BackgroundImage.png"/>
            </Grid.Background>
    </Grid>
    

    If you want to create a style resource, you can set the value like so

    <phone:PhoneApplicationPage.Resources>
        <Style x:Key="GridStyle1" TargetType="Grid">
            <Setter Property="Background">
                <Setter.Value>
                    <ImageBrush ImageSource="/BackgroundImage.png" Stretch="Fill"/>
                </Setter.Value>
            </Setter>
        </Style>
    </phone:PhoneApplicationPage.Resources>
    
    <Grid Style="{StaticResource GridStyle1}"/>
    

    I recommend using Expression Blend to help you to discover how to work with styles. It will generate control templates for you so you can see how they are structured.