代码之家  ›  专栏  ›  技术社区  ›  Kris Erickson

有没有办法在Silverlight中以编程方式更改数据/项模板?

  •  2
  • Kris Erickson  · 技术社区  · 15 年前

    我有一个列表框,它使用itemtemplate来显示图像。我希望能够更改itemtemplate中显示图像的大小。通过数据绑定,我可以更改宽度,但我能看到的唯一方法是向我绑定的类添加一个属性(比如imagesize),然后将集合中的每个项更改为具有新的imagesize。是否无法访问该数据模板中某个项的属性?

    例如。

    <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>
    

    是否仍要设置ViewBox的宽度和高度,而不将属性绑定到集合中的每个元素?

    2 回复  |  直到 6 年前
        1
  •  3
  •   Sorskoot    15 年前

    你可以使用元素绑定到这个。试试这样的:

    <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>
    
        2
  •  0
  •   Dan Davies Brackett    15 年前

    如果知道要调整的大小,可以定义许多不同的 ItemTemplate 然后换成他们。