Как реализовать добавление данных в MVVM C# WPF"?
Доброго времени суток!
Я изучаю MVVM и всю информацию я брал https://metanit.com/sharp/wpf/22.4.php
Я реализовал удаление данных, как показано в этом уроке, но добавление данных не работает, и это при том, что я использовал тот же способ, который показан в уроке.
Сам способ:
private RelayCommand addCommand;
public RelayCommand AddCommand
{
get
{
return addCommand ??
(addCommand = new RelayCommand(obj =>
{
Phone phone = new Phone();
Phones.Insert(0, phone);
SelectedPhone = phone;
}));
}
}
Пару слов о моей предметной области: есть таблица в базе данных Dish с колонками DishId, DishName, Cost, Weight.
Моя Model Dish:
class Dish : INotifyPropertyChanged
{
public Dish()
{
DishOrders = new List<DishOrder>();
}
private string dishName;
private decimal cost;
private short weight;
[Key]
public int DishId { get; set; }
[MaxLength(20)]
public string DishName
{
get { return dishName; }
set
{
dishName = value;
OnPropertyChanged();
}
}
[Column(TypeName = "money")]
public decimal Cost
{
get { return cost; }
set
{
cost = value;
OnPropertyChanged();
}
}
[Column(TypeName = "smallint")]
public short Weight
{
get { return weight; }
set
{
weight = value;
OnPropertyChanged();
}
}
public ICollection<DishOrder> DishOrders;
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName] string prop = "")
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(prop));
}
}
Моя ViewModel:
class ApplicationViewModel : INotifyPropertyChanged
{
private CafeContext db;
private Dish selectedDish;
public IEnumerable<Dish> Dishes { get; set; }
// команда добавления нового объекта
private RelayCommand addCommand;
public RelayCommand AddCommand
{
get
{
return addCommand ??
(addCommand = new RelayCommand(obj =>
{
}));
}
}
private RelayCommand removeCommand;
public RelayCommand RemoveCommand
{
get
{
return removeCommand ??
(removeCommand = new RelayCommand(obj =>
{
Dish dish = obj as Dish;
if (dish != null)
{
db.Dishes.Remove(dish);
db.SaveChanges();
}
},
obj => Dishes.Count() > 0));
}
}
public Dish SelectedDish
{
get { return selectedDish; }
set
{
selectedDish = value;
OnPropertyChanged();
}
}
public ApplicationViewModel()
{
db = new CafeContext();
db.Dishes.Load();
Dishes = db.Dishes.Local.ToBindingList();
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName] string prop = "")
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(prop));
}
}
Мой View:
public partial class dish : Page
{
public dish()
{
InitializeComponent();
DataContext = new ApplicationViewModel();
}
}
XAML-код:
<Page x:Class="cafe.Pages.dish"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:vm="clr-namespace:cafe.ViewModels"
xmlns:local="clr-namespace:cafe.Pages"
mc:Ignorable="d"
d:DataContext="{d:DesignInstance Type=vm:ApplicationViewModel}"
d:DesignHeight="450" d:DesignWidth="800"
Title="dish">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="0.8*" />
</Grid.ColumnDefinitions>
<ListBox Grid.Column="0" ItemsSource="{Binding Dishes}"
SelectedItem="{Binding SelectedDish}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Margin="5">
<TextBlock FontSize="18" Text="{Binding Path=DishName}" />
<TextBlock Text="{Binding Path=Cost}" />
<TextBlock Text="{Binding Path=Weight}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<StackPanel Grid.Column="1" Orientation="Horizontal">
<Button Command="{Binding AddCommand}" Margin="0,275,0,110" Width="80" Content="+">
</Button>
<Button Command="{Binding RemoveCommand}"
CommandParameter="{Binding SelectedDish}" Margin="0,275,0,110" Width="80" Content="-">
</Button>
</StackPanel>
<StackPanel Grid.Column="1" DataContext="{Binding SelectedDish}">
<TextBlock Text="Блюдо" />
<TextBox Text="{Binding DishName, UpdateSourceTrigger=PropertyChanged}" />
<TextBlock Text="Цена" />
<TextBox Text="{Binding Cost, UpdateSourceTrigger=PropertyChanged}" />
<TextBlock Text="Вес" />
<TextBox Text="{Binding Weight, UpdateSourceTrigger=PropertyChanged}" />
</StackPanel>
</Grid>
</Page>