将数据模型中的整型变量转换为Image对象,本测试代码将模型中的整型变量表示几颗星,在界面转换为实际的图片,效果如下:
1. 创建数据模型
public class Movie
{
public string Title { get; set; }
public int Rating { get; set; }
}
2. 创建数据集
public class Movies
{
public List<Movie> MovieList { get; set; } = GetMovieList();
public static List<Movie> GetMovieList()
{
return new List<Movie>()
{
new Movie(){Title="MOVIE One", Rating=3},
new Movie(){Title="MOVIE Two", Rating=1},
new Movie(){Title="MOVIE Three", Rating=5},
new Movie(){Title="MOVIE Four", Rating=4}
}.ToList();
}
}
3.界面添加 DataContent
<Window.DataContext>
<local:Movies/>
</Window.DataContext>
4. 添加将Int 转换为Image的转换类
using System.Windows.Data;
public class IntToStar : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var list = new List<string>();
if(value is int j)
{
for (int i = 0; i < j; i++)
{
list.Add("goldstar.png");
}
}
return list;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
5. 添加界面资源
<Window.Resources>
<local:IntToStar x:Key="int2Star"></local:IntToStar>
</Window.Resources>
6. 添加数据绑定
<StackPanel>
<TextBlock FontSize="40" FontWeight="Black" Margin="5">Movie Rating</TextBlock>
<ListBox FontSize="20" ItemsSource="{Binding MovieList}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Foreground="Green" Text="{Binding Title}" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="3"/>
<!--<TextBlock Text="{Binding Rating}" /> -->
<ListBox ItemsSource="{Binding Rating, Converter={StaticResource int2Star}}">
<ListBox.ItemTemplate>
<DataTemplate>
<Image Source="{Binding }" Width="30" Height="30"/>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
网友评论