我有一个Usercontrol,其中包含一个列表视图和一个按钮。
我想列出单击按钮时要自动添加到列表视图中的项目。
谢谢
public List<PhotosGrid> AddPicture = new List<PhotosGrid>();
public EditPhotosUserControl()
{
this.InitializeComponent();
AddPicture.Add(new PhotosGrid { Picture = "/Assets/FamilyOfficeImg/car1.png", placeHolder = "Car Side View", Caption = "Side View" });
AddPicture.Add(new PhotosGrid { Picture = "/Assets/FamilyOfficeImg/interior.png", placeHolder = "Car Interior View", Caption = "Interior View" });
PhotosGridView.ItemsSource = AddPicture;
}
private void AddButton_Click(object sender, RoutedEventArgs e)
{
AddPicture.Add(new PhotosGrid { Picture = "", placeHolder = "Car Interior View", Caption = "Interior View" });
PhotosGridView.ItemsSource = AddPicture;
}
public class PhotosGrid
{
public string Picture { get; set; }
public string placeHolder { get; set; }
public string Caption { get; set; }
}
答案 0 :(得分:0)
您需要将PhotosGrid
班级更改为实施INotifyPropertyChanged
,这样您就不需要重复设置ItemsSource
。
以下是我将如何做到这一点。
public class PhotosGrid : INotifyPropertyChanged
{
private string _picture;
public string Picture
{
get { return _picture; }
set { _picture = value; OnPropertyChanged("Picture"); }
}
private string _placeHolder;
public string PlaceHolder
{
get { return _placeHolder; }
set { _placeHolder = value; OnPropertyChanged("PlaceHolder"); }
}
private string _caption;
public string Caption
{
get { return _caption; }
set { _caption = value; OnPropertyChanged("Caption"); }
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
接下来,您需要将AddPicture从List
更改为ObservableCollection
,以便可以使用INotifyPropertyChanged
。因此,UserControl
将是
public sealed partial class EditPhotosUserControl : UserControl
{
public ObservableCollection<PhotosGrid> AddPicture = new ObservableCollection<PhotosGrid>();
public EditPhotosUserControl()
{
this.InitializeComponent();
AddPicture.Add(new PhotosGrid { Picture = "", PlaceHolder = "Car Side View", Caption = "Side View" });
AddPicture.Add(new PhotosGrid { Picture = "", PlaceHolder = "Car Interior View", Caption = "Interior View" });
PhotosGridView.ItemsSource = AddPicture;
}
private void Button_Tapped(object sender, TappedRoutedEventArgs e)
{
AddPicture.Add(new PhotosGrid { Picture = "", PlaceHolder = "Car Interior View", Caption = "Interior View" });
}
}
这将照顾您的 我希望在点击addButton时自动添加新项目
最终输出。
祝你好运。