我发现此代码将图片添加到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);
Run Code Online (Sandbox Code Playgroud)
背后的XAML很简单:
<ListView Name="Thumbnails" Margin="10,10,804,10" >
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Columns="1"/>
</ItemsPanelTemplate>
</ListView.ItemsPanel>
</ListView>
Run Code Online (Sandbox Code Playgroud)
我还发现其他几个代码,但它们只是将图像位置显示为字符串而不是图像.你能帮我解决一下吗?
这可以添加到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>
Run Code Online (Sandbox Code Playgroud)
你需要一个模型:
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 { };
Run Code Online (Sandbox Code Playgroud)
}
以及代码背后的示例:
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);
}
Run Code Online (Sandbox Code Playgroud)
}
这是解决此问题的最简单,最快捷的方法.如果你需要MVVM只需举手,我们就可以得到一个Command而不是那个Click事件.还有一件事,你有一个图像列表吗?如果是这样,我们将不得不使用ObservableCollection并实例化许多模型以便为所有按钮提供信息.
ImageSource是我的程序集名称.
图像是在我的项目中创建的文件夹.
为了填充ListView,您需要这样ObservableCollection<Model>定义:
public ObservableCollection<Model> models { get; set; }
Run Code Online (Sandbox Code Playgroud)
在构造函数中初始化它:
models = new ObservableCollection<Model>();
Run Code Online (Sandbox Code Playgroud)
并向其添加一些Model实例,其图像路径设置如上所示.
| 归档时间: |
|
| 查看次数: |
555 次 |
| 最近记录: |