开发者

Is there any way to programmatically change a Data/ItemTemplate in Silverlight?

开发者 https://www.devze.com 2022-12-26 19:20 出处:网络
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

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 collection 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}"/>
        </V开发者_如何转开发iewbox>            
    </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?


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>


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号