作者:游你精彩_980_469 | 来源:互联网 | 2024-10-20 11:26
篇首语:本文由编程笔记#小编为大家整理,主要介绍了WPF动态添加带有detals的ListViewItem相关的知识,希望对你有一定的参考价值。
我想添加ListViewItem与更改的细节,如图像的链接,文本框中的文本等。我该怎么办?
我想创建一个函数,它将添加相同的代码,就像我向您展示的更改细节。
答案
您可以使用WPF Listview的ItemTemplate和ItemsSource属性以及Binding概念。
举个例子,从你的问题开始:
您可以将以下代码添加到新WPF项目的MainWindow文件中:MainWindow.xaml文件应如下所示:
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" Title="MainWindow" > VerticalAlignment="Top" HorizOntalAlignment="Left" Margin="10" COntent="Add item"/> Margin="10" ItemsSource="{Binding Tracks}" Foreground="LightSteelBlue"> VerticalAlignment="Center" /> VerticalAlignment="Center"> TextTrimming="CharacterEllipsis" VerticalAlignment="Center" /> Margin="10,0" VerticalAlignment="Center" />
MainWindow.xaml.cs文件应如下所示:
using System; using System.Collections.ObjectModel; using System.Windows; using System.Windows.Media; using System.Windows.Media.Imaging; namespace WpfApp1 { /// /// Interaction logic for MainWindow.xaml /// public partial class MainWindow : Window { public ObservableCollection Tracks { get; set; } public MainWindow() { InitializeComponent(); this.DataCOntext= this; Tracks = new ObservableCollection(); AddTrack("01","Three Days Grace - I Hate Everything About You (Official Music Video)", "3:45", new BitmapImage(new Uri("pack://application:,,,/WpfApp1;component/Resources/pobrane.jpg"))); } public void AddTrack (string number, string name, string length, ImageSource image) { var track = new Track(); track.Number = number; track.Name = name; track.Length = length; track.Image = image; Tracks.Add(track); } private void Button_Click(object sender, RoutedEventArgs e) { AddTrack("01", "Three Days Grace - I Hate Everything About You (Official Music Video)", "3:45", new BitmapImage(new Uri("pack://application:,,,/WpfApp1;component/Resources/pobrane.jpg"))); } } public class Track { public string Number { get; set; } public string Name { get; set; } public string Length { get; set; } public ImageSource Image { get; set; } } }
当然,这只是一个起点。您应继续搜索并阅读MVVM概念并将逻辑移至视图模型。