【问题标题】:Change listview image based on binded value根据绑定值更改列表视图图像
【发布时间】:2025-12-04 08:05:01
【问题描述】:
我的程序连接到一个 mysql 数据库,然后将数据存储到一个列表视图中。我想在列表中显示项目的评级以显示为图片而不是数字。看着这个response,我想出了如何使用数据触发器显示不同的图像,但我需要一种方法来指定一个数字范围。例如,0-10 = 0stars.png,11-50 = 1stars.png,等等......
任何帮助将不胜感激。
编辑:
经过一番思考,我相信我可以在加载列表视图后运行一个函数,这是一个 for 循环,它将从列中的每一行获取值,决定它所在的数字范围,然后将其重新绑定到列表视图.这会有效吗?
【问题讨论】:
标签:
c#
mysql
wpf
listview
【解决方案1】:
你可以用转换器来做到这一点
- 将 ItemsSource 绑定到您的号码列表
- 编写一个评分转换器将数字转换为图像
- 更改 ItemTemplate 以显示图像
例如
-
xaml
<Window
Name="ThisWnd"
xmlns:local="clr-namespace:YourConverter's Namespace" <!-- the namespace of your converter. -->
...>
<Window.Resource>
<local:RatingConverter x:Key="RatingConverter"/>
</Window.Resources>
<ListView ItemsSource="{Binding Items, ElementName=ThisWnd}">
<ListView.ItemTemplate>
<DataTemplate>
<Image Source="{Binding Path=., Converter={StaticResource RatingConverter}}">
</Image>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Window>
-
后面的代码
public partial class MainWindow : Window
{
public List<int> Items
{
get;
set;
}
}
[ValueConversion(typeof(int), typeof(Image))]
public class RatingConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
int rate = (int)value;
string imagePath = "1star.png";
if (rate > 10)
{
imagePath = "2star.png";
}
return new BitmapImage(new Uri(imagePath, UriKind.Relative));
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}