我创建了以下Listbox.Itemtemplate:
<ListBox.ItemTemplate>
<DataTemplate>
<Image Name="ChannelImage" Source="{Binding ImageUrl}" Width="56" Height="56" Margin="0,0,28,0" Tap="ChannelImage_Tap" Opacity="0.5"/>
</DataTemplate>
</ListBox.ItemTemplate>
默认情况下,ItemTemplate中的图像应该具有不透明度0.5,现在我想&#34;突出显示&#34; (将不透明度设置为1.0)用户点击图像时的图像。 我使用以下代码(Tap =&#34; ChannelImage_Tap&#34;):
private void ChannelImage_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
((Image)sender).Opacity = 1.0;
}
但是,当用户点击另一张图片时,我不知道如何将图像设置回不透明度。
答案 0 :(得分:1)
在ListBox selection_change事件中执行以下代码,而不是image_tap
//I assume your listbox selection changed is ListBoxImage_Selectionchange
//ListBoxImage is your ListBox name
// LastSelectedIndex define globally
int LastSelectedIndex =0;
private void ListBoxImage_Selectionchange(object sender, SelectionChangedEventArgs e)
{
if (ListBoxImage.SelectedIndex == -1)
return;
if(LastSelectedIndex>0)
{
ListBoxItem lastItem =this.ListImage.ItemContainerGenerator.ContainerFromIndex(LastSelectedIndex) as ListBoxItem;
Image lastImage = FindFirstElementInVisualTree<Image>(lastItem);
lastImage.Opacity = 0.5;
}
ListBoxItem selectedItem = this.ListImage.ItemContainerGenerator.ContainerFromIndex(ListImage.SelectedIndex) as ListBoxItem;
Image selectedImage = FindFirstElementInVisualTree<Image>(selectedItem);
selectedImage.Opacity = 1.0;
LastSelectedIndex = ListBoxImage.SelectedIndex;
ListImage.SelectedIndex = -1;
}
private T FindFirstElementInVisualTree<T>(DependencyObject parentElement) where T : DependencyObject
{
var count = VisualTreeHelper.GetChildrenCount(parentElement);
if (count == 0)
return null;
for (int i = 0; i < count; i++)
{
var child = VisualTreeHelper.GetChild(parentElement, i);
if (child != null && child is T)
{
return (T)child;
}
else
{
var result = FindFirstElementInVisualTree<T>(child);
if (result != null)
return result;
}
}
return null;
}