views:

136

answers:

2

So I have a Listbox, which is using an ItemTemplate to display an image. I want to be able to change the size of the displayed image in the ItemTemplate. Through databinding I can change the Width, but the only way I can see how to do this is to add a Property (Say, ImageSize) to the class I am binding to and then change every item in the colleciton to have a new ImageSize. Is there no way to access the property of an item in that Datatemplate?

E.g.

<navigation:Page.Resources>
    <DataTemplate x:Key="ListBoxItemTemplate">            
        <Viewbox Height="100" Width="100">
             <Image Source="{Binding Image}"/>
        </Viewbox>            
    </DataTemplate>        
</navigation:Page.Resources>
<Grid>
    <ListBox ItemTemplate="{StaticResource ListBoxItemTemplate}" ItemSource="{Binding Collection}"/>
</Grid>

Is there anyway to set the Width and Height of the viewbox without binding a property to every element in the collection?

A: 

If you know the sizes to which you'll be resizing, you could define a number of different ItemTemplates and switch bewteen them.

DDaviesBrackett
Should be based on a slider, so I don't think I want to create 500 ItemTemplates.
Kris Erickson
That won't work, then. Oh well.
DDaviesBrackett
+3  A: 

You can use element binding to this. Try something like this:

<UserControl.Resources>        
  <DataTemplate x:Key="ListBoxItemTemplate">            
    <Viewbox Height="{Binding Value, ElementName=slider1}" 
             Width="{Binding Value, ElementName=slider1}">
      <Image Source="{Binding Image}"/>
    </Viewbox>                          
  </DataTemplate>
</UserControl.Resources>

<Grid x:Name="LayoutRoot" Background="White">
  <Grid.RowDefinitions>
    <RowDefinition Height="205*" />
    <RowDefinition Height="95*" />
  </Grid.RowDefinitions>
  <ListBox ItemTemplate="{StaticResource ListBoxItemTemplate}"
           ItemSource="{Binding Collection}"/>
  <Slider x:Name="slider1" Value="100" Maximum="250" Grid.Row="1"/>
</Grid>
Sorskoot
ElementName bindings will only work in Silverlight 3 and higher.. Since he is using silverlight 4, it should work! :)
Arcturus
So using this, I could have a hidden Textbox or something and use that to update the template programatically? Or is that hacky and there is a better way to do it?
Kris Erickson
I think you could even name the UserControl and use a custom property on the UserControl. If you do that, make sure you implement INotifyPropertyChanged and raise the PropertyChanged event when changing this property.
Sorskoot
I'll try that, that sounds perfect...
Kris Erickson