0

我的程序连接到 mysql 数据库,然后将数据存储到列表视图中。我想在列表中显示项目的评级以显示为图片而不是数字。看着这个响应,我想出了如何使用数据触发器显示不同的图像,但我需要一种方法来指定一个数字范围。例如,0-10 = 0stars.png,11-50 = 1stars.png,等等......

任何帮助将不胜感激。

编辑:经过一番思考,我相信我可以在加载列表视图后运行一个函数,这是一个 for 循环,它将从列中的每一行获取值,决定它所在的数字范围,然后将其重新绑定到列表视图。这会有效吗?

4

1 回答 1

1

您可以使用转换器来完成

  • 将 ItemsSource 绑定到您的号码列表
  • 编写一个评分转换器将数字转换为图像
  • 更改 ItemTemplate 以显示图像

例如

  • xml

    <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();
        }
    }
    
于 2013-09-15T03:35:22.007 回答