Modify data template properties of listbox in code behind
I have a listbox in XAML as per the code shown below.
<ListBox name="myListBox">
<ListBox.ItemTemplate>
<DataTemplate>
<Image Source="{Binding Path=Image}" Width="175" Height="175" VerticalAlignment="Center" HorizontalAlignment="Center"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
At runtime based on a condition, I want to change the height
and width
properties t开发者_运维技巧o another value using code behind. Please can someone guide me in achieving the desired functionality.
Many Thanks
I think the easiest way to achieve this is probably to bind the Width and Height of the Image to two properties. If you want to change the Width and Height of all Images you can use two Properties in code behind and if you want to be able to do it individually then just do the same but bind against Properties in the Collection items.
<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>
and in code behind you define two Properties
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;
}
This way, the ListBoxItems will increase/decrease in size with the Width/Height of the Images.
精彩评论