2010-11-15 60 views
2

根據下面顯示的代碼,我在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

回答

2

我認爲實現這一目標的最簡單的方法可能是寬度和圖像的高度綁定到兩個屬性。如果你想改變所有圖像的寬度和高度,你可以在後面的代碼中使用兩個屬性,如果你想能夠單獨做到這一點,只需做相同的事情,但綁定到收集項目中的屬性。

<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將增加大小與圖像的寬度/高度/減少。