在代码中修改列表框的数据模板属性

问题描述:

根据下面显示的代码,我在XAML中有一个列表框。在代码中修改列表框的数据模板属性

<ListBox name="myListBox"> 
    <ListBox.ItemTemplate> 
    <DataTemplate> 
     <Image Source="{Binding Path=Image}" Width="175" Height="175" VerticalAlignment="Center" HorizontalAlignment="Center"/> 
    </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 

在运行时基于一个条件,我想改变heightwidth属性,使用代码隐藏另一个值。请有人指导我实现所需的功能。

非常感谢

+0

列表框或列表框项目的高度和宽度? – 2010-11-15 13:57:03

我认为实现这一目标的最简单的方法可能是宽度和图像的高度绑定到两个属性。如果你想改变所有图像的宽度和高度,你可以在后面的代码中使用两个属性,如果你想能够单独做到这一点,只需做相同的事情,但绑定到收集项目中的属性。

<ListBox name="myListBox"> 
    <ListBox.ItemTemplate> 
     <DataTemplate> 
      <Image Source="{Binding Path=Image}" 
        Width="{Binding ElementName=myWindow, 
            Path=ListBoxTemplateWidth}" 
        Height="{Binding ElementName=myWindow, 
            Path=ListBoxTemplateHeight}" 
        VerticalAlignment="Center" 
        HorizontalAlignment="Center"/> 
     </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 

,并在后面的代码定义两个属性

private double m_listBoxTemplateHeight; 
public double ListBoxTemplateHeight 
{ 
    get 
    { 
     return m_listBoxTemplateHeight; 
    } 
    private set 
    { 
     m_listBoxTemplateHeight = value; 
     OnPropertyChanged("ListBoxTemplateHeight"); 
    } 
} 
private double m_listBoxTemplateWidth; 
public double ListBoxTemplateWidth 
{ 
    get 
    { 
     return m_listBoxTemplateWidth; 
    } 
    private set 
    { 
     m_listBoxTemplateWidth = value; 
     OnPropertyChanged("ListBoxTemplateWidth"); 
    } 
} 

if (someCondition == true) 
{ 
    ListBoxTemplateHeight = 200; 
    ListBoxTemplateWidth = 200; 
} 

这样,ListBoxItems将增加大小与图像的宽度/高度/减少。