我正在尝试将两个数组列表中的数据导入窗口。第一个数组列表包含图像,第二个数组列表包含电影名称。
布局将在海报下方显示电影海报以及相关电影的名称。我目前使用的代码似乎没有正常工作,因为我只在窗口中显示图像但没有文本。
这是我当前的XAML代码:
<Window.Resources>
<DataTemplate x:Key="ItemTemplate">
<WrapPanel Orientation="Vertical">
<Image Width="200" Height="300" Stretch="Fill" Source="{Binding}"/>
<TextBlock Text="{Binding movie_names}" HorizontalAlignment="Center"/>
</WrapPanel>
</DataTemplate>
</Window.Resources>
<Grid x:Name="movie_grid">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition />
</Grid.RowDefinitions>
<ListView Grid.Row="1"
Name="MovieListView"
ItemTemplate="{StaticResource ItemTemplate}"
ItemsSource="{Binding Path = movie_posters_list}">
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Columns="5" />
</ItemsPanelTemplate>
</ListView.ItemsPanel>
</ListView>
<TextBlock Name="SampleTextBlock"
Text="{Binding Path=movie_names}"
DataContext="{StaticResource ItemTemplate}" />
</Grid>
</Window>
这里是C#代码:
public partial class MoviePanel : Window {
public MoviePanel() {
InitializeComponent();
}
List<ImageSource> movie_posters_list = new List<ImageSource>();
List<String> movie_names = new List<String>();
String regex_pattern = @"\\([\w ]+).(?:jpg|png)$";
public void LoadImages() {
//Image current_image;
String movie_poster_path = @"C:\Users\Vax\Desktop\movie_posters";
List<String> filenames = new List<String>(System.IO.Directory.EnumerateFiles(movie_poster_path, "*.jpg"));
foreach (String filename in filenames) {
this.movie_posters_list.Add(new BitmapImage(new Uri(filename)));
Match regex_match = Regex.Match(filename.Trim(), regex_pattern);
String matched_movie_name = regex_match.Groups[1].Value;
this.movie_names.Add(matched_movie_name);
}
MovieListView.ItemsSource = movie_posters_list;
MovieListView.DataContext = movie_names;
}
}
我认为问题源于对数据的约束,但我不确定我做错了什么。
答案 0 :(得分:2)
创建一个模型类并将电影名称和图像包装到其中。
public class MovieDetail
{
public ImageSource Image { get; set; }
public string Name { get; set; }
}
调用LoadImages时,将此模型的实例添加到ListView中。并修改datatemplate以绑定Name和Image。
List<MovieDetail> movies = new List<MovieDetail>();
foreach (String filename in filenames)
{
Match regex_match = Regex.Match(filename.Trim(), regex_pattern);
String matched_movie_name = regex_match.Groups[1].Value;
movies.Add(new MovieDetail { Image = new BitmapImage(new Uri(filename)), Name = matched_movie_name });
}
MovieListView.ItemsSource = movies;
DataTemplate,
<DataTemplate x:Key="ItemTemplate">
<WrapPanel Orientation="Vertical">
<Image Width="200"
Height="300"
Stretch="Fill"
Source="{Binding Image}" />
<TextBlock Text="{Binding Name}"
HorizontalAlignment="Center" />
</WrapPanel>
</DataTemplate>