【解決方法】ListView を使用した WPF MVVM ICommnad

プログラミングQA


こんにちは、

WPF の ICommand と MVVM について質問があります。

イベントを処理する最も一般的な方法は、インターフェイス ICommand を使用することであることがわかりました。

ボタンにコマンドを追加したい場合は、次のようなことを行うと理解しています。
<Button Command="{MyCommand}" />

しかし、ListViewのselectionchangedまたは何かへのコマンドを作成する方法がわかりません。

誰か良い例を知っている人、または簡単なコードを教えてくれる人はいますか?

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

また会ったね、
listView での SelectionChanged の Icommand 実装にはまだ問題があります。
こんな投稿を見つけました: http://blog.fossmo.net/post/How-to-create-an-attached-property-in-WPF-using-a-ComboBox.aspx[^] しかし、「MyCommand は CAG からの DelegateCommand になれる」という言葉が何を意味するのかわかりません。 CAG クラスはどのようなものになるでしょうか?

解決策 2

まず第一に、ICommand はイベントをサポートするメカニズムではありません。 これは、WPF または Silverlight でコマンド ベースの機能を実行するためのメカニズムです。 私がこれを言う理由は、イベントが行うべきことを超えているためです。ICommand インターフェイスは CanExecute メソッドもサポートしているため、コマンド インフラストラクチャでは、何かが起こるかどうかを判断して UI に影響を与えることもできます。 何かが ICommand をサポートしている場合、UI は実際にこのメソッドを考慮するため、CanExecute が false を返した場合はボタンを押すことができません。

ご存知のとおり、ICommand はコマンド バインドをサポートしていないため、変更された選択に ICommand をバインドできません。 最初は、これは現実的な問題のように思えますが、これをサポートする解決策が多数あります。 おそらく最良の実装は、MVVM Light での EventToCommand サポートです。 ここ[^]。

ローランはこの動作を使用してデモンストレーションします ここ[^]。

解決策 1

私が出会った最良の例では、添付プロパティを使用しています。 この良い例は、Claus Conrads のブログでご覧いただけます。 WPF ListView MVVM と ICommand が欠落しています[^]。 添付プロパティはあらゆる用途に使用できるため、使い慣れる価値があります。

お役に立てれば

解決策 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をコピーしました