我发现这段代码可以将图片添加到 WPF 中的 ListView 中。但是它只显示图像位置而不是实际图像:
var image = new BitmapImage();
string fileName = @"C:\Peak Sourcing\Work\ppt_test\slides_png\slide1.png";
using (var stream = new FileStream(fileName, FileMode.Open))
{
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.StreamSource = stream;
image.EndInit();
}
ListBoxItem item = new ListBoxItem();
Thumbnails.Items.Add(image);
背后的 XAML 很简单:
<ListView Name="Thumbnails" Margin="10,10,804,10" >
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Columns="1"/>
</ItemsPanelTemplate>
</ListView.ItemsPanel>
</ListView>
我还发现了一些其他代码,但它们都只是将图像位置显示为字符串而不是图像。你能帮我解决这个问题吗?
最佳答案
这可以添加到 XAML 中:
<ListView x:Name="lv" Background="WhiteSmoke"
Height="500"
ItemsSource="{Binding models}">
<ListView.View>
<GridView>
<GridViewColumn>
<GridViewColumn.CellTemplate>
<DataTemplate>
<Image Source="{Binding ImagePath}"
HorizontalAlignment="Left"
Stretch="Fill"
Height="100"
Width="100"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
您需要一个模型:
public class Model : INotifyPropertyChanged
{
private Uri _ImagePath;
public Uri ImagePath
{
get
{
return _ImagePath;
}
set
{
_ImagePath = value;
PropertyChanged(this, new PropertyChangedEventArgs("ImagePath"));
}
}
public event PropertyChangedEventHandler PropertyChanged = delegate { };
}
以及背后代码的示例:
public partial class MainWindow : Window
{
public Model ImageModel { get; set; }
public MainWindow()
{
InitializeComponent();
ImageModel = new Model();
ImageModel.ImagePath = new Uri(@"/ImageSource;component/Images/Image1.jpg", UriKind.RelativeOrAbsolute);
this.DataContext = ImageModel;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
ImageModel.ImagePath = new Uri(@"/ImageSource;component/Images/Image2.jpg", UriKind.RelativeOrAbsolute);
}
}
这是解决此问题最简单、最快的方法。如果您需要 MVVM,只需举手,我们就可以获得 Command 而不是 Click 事件。还有一件事,你有图片列表吗?如果是这样,我们将必须使用 ObservableCollection 并实例化许多模型才能提供所有按钮。
ImageSource 是我的程序集名称。
Images 是在我的项目中创建的文件夹。
为了填充 ListView,您需要 ObservableCollection<Model>
定义如下:
public ObservableCollection<Model> models { get; set; }
在构造函数中初始化它:
models = new ObservableCollection<Model>();
并向其中添加一些模型实例,其图像路径设置如上所示。
关于c# - 如何在 ListView 中显示实际图像而不是其位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30750891/