我有一个列表控件,每个项目包含两个图像和文本。在单击每个项目时,我想在所选列表项上隐藏或显示所选图像。
这是 XAML 代码片段:
<ListBox x:Name="list" SelectionChanged="list_SelectionChanged" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Name}"/>
<Image Source="{Binding ImagePath}" Stretch="None"/>
<Image Source="{Binding ImagePath}" Stretch="None"
Visibility="{Binding ImageVisibility,
Converter={StaticResource boolVisibilityConverter}}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
C#代码:
dataSource = new ObservableCollection<ImageData>()
{
new ImageData(){Name = "User1:", ImagePath="/Images/user1.png", ImageVisibility = false},
new ImageData(){Name = "User1:", ImagePath="/Images/user1.png", ImageVisibility = true},
new ImageData(){Name = "User1:", ImagePath="/Images/user1.png", ImageVisibility = true},
new ImageData(){Name = "User2:", ImagePath="/Images/user2.png", ImageVisibility = true}
};
列表选择更改事件:
private void list_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
((ImageData)(((object[])(e.AddedItems))[0])).ImageVisibility = false;
list.UpdateLayout();
}
图像数据类:
public class ImageData
{
public string ImagePath { get; set; }
public string Name { get; set; }
public bool ImageVisibility { get; set; }
}
图像可见性转换器:
public class BooleanToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
bool flag = false;
if (value is bool)
{
flag = (bool)value;
}
else if (value is bool?)
{
bool? nullable = (bool?)value;
flag = nullable.HasValue ? nullable.Value : false;
}
return (flag ? Visibility.Visible : Visibility.Collapsed);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return ((value is Visibility) && (((Visibility)value) == Visibility.Visible));
}
}
请帮我完成这样的功能。