WPF MVVM ICommnad avec ListView

la programmation


Bonjour,

J’ai une question sur ICommand et MVVM dans WPF.

J’ai vu que la manière la plus courante de gérer les événements consiste à utiliser l’interface ICommand.

Je comprends que si je veux ajouter une commande à un bouton, je fais quelque chose comme ceci :
<Button Command="{MyCommand}" />

Mais je ne comprends pas comment créer une commande pour selectionchanged ou quelque chose pour un ListView ?

Quelqu’un connaît-il de bons exemples ou pourrait-il m’aider avec un code simple ?

————————————————– ————————————————-

Re-bonjour,
J’ai encore des problèmes avec l’implémentation Icommand de SelectionChanged sur listView.
J’ai trouvé ce post : http://blog.fossmo.net/post/How-to-create-an-attached-property-in-WPF-using-a-ComboBox.aspx[^] mais je ne suis pas sûr de ce qu’il veut dire par : “MyCommand peut être une DelegateCommand de CAG.” À quoi pourrait ressembler une classe CAG ?

Solution 2

Tout d’abord, ICommand n’est pas le mécanisme permettant de prendre en charge les événements. C’est le mécanisme par lequel vous devez exécuter des fonctionnalités basées sur des commandes dans WPF ou Silverlight. La raison pour laquelle je dis cela est parce que cela va au-delà de ce qu’un événement devrait faire – avec une infrastructure de commande, vous pouvez également affecter l’interface utilisateur en déterminant si quelque chose peut se produire ou non, car l’interface ICommand prend également en charge une méthode CanExecute. Lorsque quelque chose prend en charge ICommand, l’interface utilisateur prend en compte cette méthode, de sorte que vous ne pouvez pas appuyer sur un bouton lorsque CanExecute renvoie false.

Comme vous le savez maintenant, vous ne pouvez pas lier un ICommand à une sélection modifiée car il ne prend pas en charge la liaison de commande. À première vue, cela semble être un réel problème, mais il existe un certain nombre de solutions pour y remédier. La meilleure implémentation est probablement la prise en charge EventToCommand dans MVVM Light que vous pouvez trouver ici[^].

Laurent démontre en utilisant ce comportement ici[^].

Solution 1

Les meilleurs exemples que j’ai rencontrés utilisent les propriétés attachées. Un bon exemple de cela peut être trouvé sur le blog Claus Conrads. WPF ListView MVVM et ICommand manquant[^]. Les propriétés attenantes peuvent être utilisées pour toutes sortes de choses et valent vraiment la peine de s’y familiariser.

J’espère que cela t’aides

Solution 4

For handling the SelectionChanged event in a ListView, there are two possible approaches: either by attaching a behavior or by using the Interaction framework.

For complete solution,I have created an example for it. follow the following steps:

==> Install Nuget package of "Microsoft.Xaml.Behaviors"

==>MainWindow.Xaml will be like below

<Window x:Class="WpfApp3.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp3"
         xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <ListView ItemsSource="{Binding Items}" 
          SelectedItem="{Binding SelectedItem}">
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="SelectionChanged">
                    <i:InvokeCommandAction Command="{Binding SelectionChangedCommand}"/>
                </i:EventTrigger>
            </i:Interaction.Triggers>
            <!-- ListView content here -->
        </ListView>

    </Grid>
</Window>

==>MainWindow.Xaml.cs

using System.Windows;

namespace WpfApp3
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            DataContext = new MainViewModel();
        }
    }
}

==>I've developed a ViewModel tailored for the provided XAML, facilitating the binding of commands with the view.

using System;
using System.Collections.Generic;
using System;
using System.Collections.ObjectModel;
using System.Windows.Input;

namespace WpfApp3
{
    public class MainViewModel
    {
        public ObservableCollection<string> Items { get; set; }

        public ICommand SelectionChangedCommand { get; set; }

        public MainViewModel()
        {
            Items = new ObservableCollection<string>
            {
                "Item 1",
                "Item 2",
                "Item 3"
            };

            SelectionChangedCommand = new RelayCommand(OnSelectionChanged);
        }

        private void OnSelectionChanged(object selectedItem)
        {
            // Handle selection changed logic here
            Console.WriteLine("Selected item: " + selectedItem);
        }
    }
}

==>RelayCommand.cs class 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace WpfApp3
{
    public class RelayCommand : ICommand
    {
        private readonly Action<object> _execute;
        private readonly Func<object, bool> _canExecute;

        public RelayCommand(Action<object> execute, Func<object, bool> canExecute = null)
        {
            _execute = execute ?? throw new ArgumentNullException(nameof(execute));
            _canExecute = canExecute;
        }

        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }

        public bool CanExecute(object parameter)
        {
            return _canExecute == null || _canExecute(parameter);
        }

        public void Execute(object parameter)
        {
            _execute(parameter);
        }
    }
}

コメント

タイトルとURLをコピーしました