Search code examples
c#visual-studiowindows-phone-7expression-blend

Dynamically assign style resource


Let's say i have the following DataTemplate:

<DataTemplate x:Key="ListBoxItemTemplate">

        <Grid HorizontalAlignment="Stretch" Width="440">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="50" />
                <ColumnDefinition />
                <ColumnDefinition Width="Auto" />
                <ColumnDefinition Width="45" />
            </Grid.ColumnDefinitions>

            <Rectangle x:Name="RECTA" Grid.ColumnSpan="4" Margin="0,0,0,8" Style="{StaticResource ListItemRed}" />

            <TextBlock Margin="1,1,0,0" TextWrapping="Wrap" Text="{Binding ItemDescription}" Grid.Column="1" />

            <Button                                
                Grid.Column="2"
                x:Name="deleteItemButton"
                BorderThickness="0"                                                                  
                Margin="-1,1,-17,0"
                Click="deleteItemButton_Click" d:LayoutOverrides="HorizontalAlignment" Grid.ColumnSpan="2">

                <Image 
                    Source="AppBar/Icons/appbar.delete.rest.png"
                    Height="58"
                    Width="49"/>

            </Button>
        </Grid>
    </DataTemplate>

And the following listbox:

<ListBox 
                    x:Name="ItemsListBox" 
                    ItemsSource="{Binding ActiveList}" 
                    Margin="8,82,8,8" Width="440" 
                    ItemTemplate="{StaticResource ListBoxItemTemplate}" />

On the data template there is a rectangle.. what i need to assign dynamically the Style="{StaticResource ListItemRed}" for each item that exists in the listbox. Style="{Binding SOMETEMPLATE}" didnt work.


Solution

  • What you need is an equivalent of WPFs DataTemplateSelector.
    Such a thing is easy to recreate. See an example at http://www.codeproject.com/Articles/92439/Silverlight-DataTemplateSelector

    Additionally, I noticed the grid in your template has more columns defined than it's using.