Diego
Diego

Reputation: 796

How to change itemTemplate of an item in itemControl at runtime in silverlihgt 4

I have a ItemControl in silverlight 4 with a Canvas as a ItemPanel, the idea is to simulate a canvas area with drag and dop items. ItemsControl has a ItemTemplate with a image and one button.

The idea is that when the button of itemTemplate Click the itemTemplate change.

Some of my code: (Items Control)

<ItemsControl ItemsSource="{Binding Devices}"
              ItemTemplate="{StaticResource deviceItemTemplate}">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <Canvas
                    HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
                    MouseLeftButtonDown="Canvas_MouseLeftButtonDown" 
                    MouseMove="Canvas_MouseMove" 
                    LostMouseCapture="Canvas_LostMouseCapture"></Canvas>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
    </ItemsControl>

(ItemTemplate)

<DataTemplate x:Key="deviceItemTemplate">
    <ContentControl>
        <Grid IsHitTestVisible="True" Background="Transparent">
            <Grid.RowDefinitions>
                <RowDefinition></RowDefinition>
                <RowDefinition Height="30"></RowDefinition>
            </Grid.RowDefinitions>
            <Image IsHitTestVisible="False" Grid.Row="0" Stretch="UniformToFill" 
                   Width="50" Height="50" 
                   Source="{Binding ImagePath}"/>
            <Button Grid.Row="1" Content="{Binding EditarDispositivoCommand.DisplayName}" Command="{Binding EditarDispositivoCommand.Command}"></Button>
        </Grid>
        <ContentControl.RenderTransform>
            <TranslateTransform X="{Binding X, Mode=TwoWay}" Y="{Binding Y, Mode=TwoWay}"></TranslateTransform>
        </ContentControl.RenderTransform>
    </ContentControl>
</DataTemplate>

I try to get that when a button in a itemTemplate is clicked the template of this item change to other template from resource.

Was that possible or i taking a bad way. Thanks a lot.

Upvotes: 0

Views: 884

Answers (2)

Darkside
Darkside

Reputation: 1739

I just used the following article to do what you suggested. I have two item templates defined for a view and can progamatically change the item template at runtime though codebehind

http://weblogs.asp.net/psheriff/archive/2010/08/25/change-templates-dynamically-in-silverlight.aspx

Hope this helps (Sample also uses a button to change the item template)

Upvotes: 0

Chad Brockman
Chad Brockman

Reputation: 1396

You could try using a DataTemplateSelector for Silverlight - it's not built in like WPF, but it can be achieved with some extra code.

Here is a good example from CodeProject: http://www.codeproject.com/KB/silverlight/SLTemplateSelector.aspx

Just add an element to you view model to specify the template...

Upvotes: 1

Related Questions