Implementeer ICommand patroon met RelayCommand voor MVVM

- Voeg RelayCommand class toe voor herbruikbare ICommand implementatie
- Vervang button click event handler door AddProductCommand in MainViewModel
- Update XAML om Command binding te gebruiken in plaats van Click event
- Verwijder business logic uit code-behind (MainWindow.xaml.cs)
- Los DataContext duplicatie op (was twee keer MainViewModel instantie)

Dit maakt de applicatie beter testbaar en volgt proper MVVM principes.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Mark Kors
2025-11-12 19:11:54 +01:00
parent 5d5ae0c5e7
commit ce63f9bff9
4 changed files with 95 additions and 17 deletions

View File

@@ -26,7 +26,7 @@
Content="Add Product"
Width="100px"
Height="25px"
Click="btnAddProduct_Click" />
Command="{Binding AddProductCommand}" />
<Label Content="Selected Product Details"
FontWeight="Bold"
FontSize="16"

View File

@@ -18,12 +18,10 @@ namespace MVVM_DEMO
/// </summary>
public partial class MainWindow : Window
{
MainViewModel viewModel = new MainViewModel();
public MainWindow()
{
InitializeComponent();
this.DataContext = viewModel;
// ViewModel is already set in XAML via Window.DataContext
comboBox.SelectionChanged += ComboBox_SelectionChanged;
// initial selection
if (comboBox.Items.Count > 0)
@@ -35,25 +33,15 @@ namespace MVVM_DEMO
private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// display selected product details
if (comboBox.SelectedItem != null)
if (comboBox.SelectedItem != null && DataContext is MainViewModel viewModel)
{
viewModel.productName= ((Product)comboBox.SelectedItem).ProductName;
viewModel.productName = ((Product)comboBox.SelectedItem).ProductName;
viewModel.productPrice = (int)((Product)comboBox.SelectedItem).Price;
viewModel.OnPropertyChanged("productName");
viewModel.OnPropertyChanged("productPrice");
}
}
private void btnAddProduct_Click(object sender, RoutedEventArgs e)
{
// toevoegen van een product in het viewmodel
Product p = new Product();
p.ProductName = $"Product {viewModel.Products.Count + 1}";
// generate a random price between 10 and 100
Random rand = new Random();
p.Price = rand.Next(10, 100);
viewModel.Products.Add(p);
}
// btnAddProduct_Click removed - now using Command binding in XAML
}
}