【问题标题】:Is there any way to programmatically change a Data/ItemTemplate in Silverlight?有没有办法以编程方式更改 Silverlight 中的 Data/ItemTemplate?
【发布时间】:2010-04-15 18:25:50
【问题描述】:

我有一个列表框,它使用 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>

是否可以在不将属性绑定到集合中的每个元素的情况下设置视图框的宽度和高度?

【问题讨论】:

    标签: silverlight xaml silverlight-4.0


    【解决方案1】:

    您可以使用元素绑定到此。试试这样的:

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

    【讨论】:

    • ElementName 绑定只能在 Silverlight 3 及更高版本中工作。由于他使用的是 silverlight 4,它应该可以工作! :)
    • 所以使用这个,我可以有一个隐藏的文本框或其他东西,并用它来以编程方式更新模板?或者这很老套,有更好的方法吗?
    • 我认为您甚至可以命名 UserControl 并在 UserControl 上使用自定义属性。如果这样做,请确保实现 INotifyPropertyChanged 并在更改此属性时引发 PropertyChanged 事件。
    【解决方案2】:

    如果您知道要调整的大小,您可以定义多个不同的ItemTemplates 并在它们之间切换。

    【讨论】:

    • 应该是基于滑块的,所以我觉得我不想创建500个ItemTemplates。
    猜你喜欢
    • 2020-04-23
    • 1970-01-01
    • 1970-01-01
    • 2020-01-14
    • 1970-01-01
    • 2021-12-13
    • 1970-01-01
    • 2020-09-23
    • 1970-01-01
    相关资源
    最近更新 更多