WPF MVVM ICommnad với ListView

lập trình


Xin chào,

Tôi có câu hỏi về ICommand và MVVM trong WPF.

Tôi đã thấy rằng cách phổ biến nhất để xử lý các sự kiện là sử dụng giao diện ICommand.

Tôi hiểu rằng nếu tôi muốn thêm lệnh vào một nút, tôi sẽ làm như sau:
<Button Command="{MyCommand}" />

Nhưng tôi không hiểu cách tạo lệnh cho phép chọn đã thay đổi hoặc thứ gì đó cho ListView?

Có ai biết bất kỳ ví dụ hay nào ở đó hoặc có thể giúp tôi với một số mã đơn giản không?

————————————————– ————————————————–

Chào bạn lần nữa nhé,
Tôi vẫn gặp vấn đề với việc triển khai SelectionChanged của Icommand tại listView.
Tôi tìm thấy bài đăng này: http://blog.fossmo.net/post/How-to-create-an-attached-property-in-WPF-USE-a-ComboBox.aspx[^] nhưng tôi không chắc ý của anh ấy là gì: “MyCommand có thể là DelegateCommand từ CAG.” Một lớp CAG có thể trông như thế nào?

Giải pháp 2

Trước hết, ICommand không phải là cơ chế hỗ trợ các sự kiện. Đây là cơ chế mà bạn nên thực hiện chức năng dựa trên lệnh trong WPF hoặc Silverlight. Lý do tôi nói điều này là vì nó vượt xa những gì một sự kiện nên làm – với cơ sở hạ tầng ra lệnh, bạn cũng có thể tác động đến giao diện người dùng bằng cách xác định liệu điều gì đó có thể xảy ra hay không vì giao diện ICommand cũng hỗ trợ phương thức CanExecute. Khi có thứ gì đó hỗ trợ ICommand, giao diện người dùng sẽ thực sự tính đến phương thức này để bạn không thể nhấn nút khi CanExecute trả về sai.

Như bạn đã biết, bạn không thể liên kết ICommand với một lựa chọn đã thay đổi vì nó không hỗ trợ liên kết lệnh. Lúc đầu, đây có vẻ là một vấn đề thực sự, nhưng có một số giải pháp hỗ trợ vấn đề này. Có lẽ cách triển khai tốt nhất là hỗ trợ EventToCommand trong MVVM Light mà bạn có thể tìm thấy đây[^].

Laurent thể hiện việc sử dụng hành vi này đây[^].

Giải pháp 1

Những ví dụ hay nhất mà tôi đã gặp sử dụng Thuộc tính đính kèm. Một ví dụ điển hình về điều này có thể được tìm thấy trên Blog của Claus Conrads WPF ListView MVVM và thiếu ICommand[^]. Các thuộc tính đính kèm có thể được sử dụng cho mọi mục đích và chắc chắn đáng để bạn sử dụng.

Hi vọng điêu nay co ich

Giải pháp 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をコピーしました