How to add items from a list to a list by clicking a button without a code?

I am new to MVVM and also pretty new to WPF. In fact, I started programming just a few months ago. MVVM really fits into the concept of binding, and for several days I’ve been trying to just make an application that allows you to select an item from the bx list, and when you click the add button, the selected item should be saved in a new list. The second list displays the last added items, and you can select the item and delete it using another button. Conditionally, I would go to the click event and decorate my code game with rather small methods, but I really want to learn how to do all this using bindings and no code. I would be very happy for any help, and please remember that I am new to this, and I really want to keep it as simple as possible :) Regards Daniela

<WrapPanel HorizontalAlignment="Center" Margin=" 10"> <ListBox x:Name="Firstbox" Width="100" ItemsSource="{Binding FoodList}" DisplayMemberPath="Name" > </ListBox> <Button Margin="10 >Select</Button> <ListBox Width="100"></ListBox> 

private list _foodList;

  public List<FoodItem> FoodList { get { return _foodList; } set { _foodList = value; } } private List<FoodItem> _newFoodList; public List<FoodItem> NewFoodList { get { return _newFoodList; } set { _newFoodList = value; } } public MainViewModel() { InitializeCommands(); GetFood(); } private void GetFood() { FoodList = new List<FoodItem>() { new FoodItem() {Name="Applepie"}, new FoodItem() {Name="Scones"} }; } 
+6
source share
1 answer
  • first you need to replace List with ObservableCollection s so that the user interface can detect when new items are added.
  • Add the SelectedItem property to the ViewModel:

     private FoodItem _selectedItem; public FoodItem SelectedItem { get { return _selectedItem;} set { _selectedItem = value; OnPropertyChanged("SelectedItem"); } } 
  • bind the SelectedItem property of the 1st ListBox with this property:

     <ListBox Width=" 100" x:Name="Firstbox" ItemsSource="{Binding FoodList}" DisplayMemberPath="Name" SelectedItem="{Binding SelectedItem}" /> 
  • bind your second ListBox to the NewFoodList property

  • create a command in ViewModel:

     private DelegateCommand _addItemCommand; public ICommand AddItemCommand { get { if (_addItemCommand == null) { _addItemCommand = new DelegateCommand(AddItem); } return _addItemCommand; } } void AddItem() { if (SelectedItem != null) NewFoodList.Add(SelectedItem); } 
  • Finally, bind the Command property to the AddItemCommand property:

     <Button Margin="10" Command="{Binding AddItemCommand}" >Select</Button> 
+7
source

Source: https://habr.com/ru/post/901393/


All Articles