3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

WPFのListView,ListBoxで選択要素変更とコマンドを結び付ける方法

Posted at

はじめに

本記事は、WPFのListView,ListBoxで選択要素変更とコマンドを結び付ける方法を備忘録として残すことを目的としています。

方法

筆者はこちらの記事を参考にしました。
以下のSampleWindowのDataContextにはSampleWindowViewModelが設定されているとします。

  • SampleWindowViewModel.cs

using Sample.ViewModels
{
    // SampleWindowViewModelのViewModel
    public class SampleWindowViewModel
    {
        // 選択変更時のコマンド
        public ICommand SelectionChangedCommand { get; }
    }
}
  • SampleWindow.xaml

<Window x:Class="Sample.Views.SampleWindow"
        xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity">

    <Grid>
        <ListView ・・・>
            <!-- ListViewのSelectionChangedイベントが発生するとSelectionChangeCommandコマンドが実行されるように設定 -->
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="SelectionChanged">
                    <i:InvokeCommandAction Command="{Biding Path = SelectionChangedCommand}" />
                </i:EventTrigger>
            </i:Interaction.Triggers>
    </Grid>
</Window>

SampleWindow.xamlの「xmlns:i=・・・」の部分でSystem.Window.Interactivityの機能を使えるように名前空間をusingしています。その後のListViewの「i:Interaction.Triggers」でトリガを設定しています。具体的には「i:EventTrigger EventName="SelectionChanged"」なので、選択変更後イベントをトリガにしてアクションを実行します。アクションは「i:InvokeCommandAction Command="{Biding Path = SlectionChangedCommand}"」なので、DataContextのSelectionChangeCommandという名前のコマンドが実行されます。具体的にはSampleWindowViewModel.SelectionChangeCommandが実行されることになります。

参考文献

3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?