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:
@@ -5,6 +5,8 @@ using System.ComponentModel;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Input;
|
||||
using MVVM_DEMO.Commands;
|
||||
using MVVM_DEMO.Models;
|
||||
|
||||
namespace MVVM_DEMO.ViewModels
|
||||
@@ -28,6 +30,9 @@ namespace MVVM_DEMO.ViewModels
|
||||
{
|
||||
_products = new ObservableCollection<Product>();
|
||||
LoadData();
|
||||
|
||||
// Initialize commands
|
||||
AddProductCommand = new RelayCommand(ExecuteAddProduct, CanExecuteAddProduct);
|
||||
}
|
||||
|
||||
// read data
|
||||
@@ -46,5 +51,28 @@ namespace MVVM_DEMO.ViewModels
|
||||
public string productName { get; set; }
|
||||
public int productPrice { get; set; }
|
||||
|
||||
// Commands
|
||||
public ICommand AddProductCommand { get; set; }
|
||||
|
||||
// Command methods
|
||||
private void ExecuteAddProduct(object? parameter)
|
||||
{
|
||||
Random random = new Random();
|
||||
int randomPrice = random.Next(10, 100);
|
||||
|
||||
Products.Add(new Product
|
||||
{
|
||||
ProductName = $"Product {Products.Count + 1}",
|
||||
Price = randomPrice
|
||||
});
|
||||
}
|
||||
|
||||
private bool CanExecuteAddProduct(object? parameter)
|
||||
{
|
||||
// You can add validation logic here
|
||||
// For now, always allow adding products
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user