前提・実現したいこと
C# WPF 初心者です。
用語の誤用/的外れな質問ありましたらご容赦ください。
リストボックスの要素の内、選択しているものだけを削除するコマンドを作りたいです。
そしてコマンドの発動条件として、リストボックス内の項目を選択していないときはボタンが押せないようにしたいです。
(リストボックスの選択モードはExtendedで行いたいです。)
リストボックスにおいて現在選択されているものを取得し、VMへ伝える方法がググっても分かりませんでした・・・
リスト用クラスにbool型のIsSelectedプロパティを用意してあるので、そちらを使った方法でも構いません。
お手数おかけしますが、ご教示よろしくお願いいたします。
該当のソースコード
XAML
1<Window x:Class="ListDelete.Views.MainWindow" 2 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 3 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 4 xmlns:prism="http://prismlibrary.com/" 5 prism:ViewModelLocator.AutoWireViewModel="True" 6 Title="ListDelete" Height="350" Width="525"> 7 8 <Window.Resources> 9 <BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" /> 10 </Window.Resources> 11 12 <Grid> 13 <ListBox HorizontalAlignment="Left" Height="184" Margin="42,73,0,0" VerticalAlignment="Top" Width="153" 14 ItemsSource="{Binding MyList}" 15 DisplayMemberPath="Name" 16 IsSynchronizedWithCurrentItem="True" 17 SelectionMode="Extended"> 18 19 <ListBox.ItemContainerStyle> 20 <Style TargetType="ListBoxItem"> 21 <Setter Property="IsSelected" Value="{Binding IsSelected.Value}" /> 22 </Style> 23 </ListBox.ItemContainerStyle> 24 25 </ListBox> 26 27 28 <Button Content="選択した項目を削除" HorizontalAlignment="Left" Margin="231,104,0,0" VerticalAlignment="Top" Width="127" 29 Command="{Binding Cmd_DeleteList}" /> 30 </Grid> 31</Window> 32
C#
1using Prism.Mvvm; 2using Reactive.Bindings; 3using System.Collections.ObjectModel; 4using System.Windows.Annotations; 5 6namespace ListDelete.ViewModels 7{ 8 public class MainWindowViewModel : BindableBase 9 { 10 //リスト 11 public ObservableCollection<Person> MyList { get; set; } = new ObservableCollection<Person>(); 12 13 //選択した要素を削除するコマンド 14 public ReactiveCommand Cmd_DeleteList { get; private set; } 15 16 public MainWindowViewModel() 17 { 18 //リスト生成 19 MyList.Add(new Person { Name = "AAA" }); 20 MyList.Add(new Person { Name = "BBB" }); 21 MyList.Add(new Person { Name = "CCC" }); 22 23 //コマンド発動条件設定 24 Cmd_DeleteList = 25 //ここにリストを選択していないときはボタンが押せないよう設定したい。 26 .ToReactiveCommand(); 27 28 コマンド動作定義 29 Cmd_DeleteList.Subscribe(()=> 30 { 31 //ここに選択した要素を削除するコマンドを追加したい。 32 }); 33 } 34 } 35 36 public class Person : BindableBase 37 { 38 public string Name { get; set; } 39 public ReactiveProperty<bool> IsSelected { get; set; } = new ReactiveProperty<bool>(); 40 } 41 42}
補足情報(FW/ツールのバージョンなど)
OS:win10
.NET Framework:4.7.2
Visual Studio 2019

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2020/09/21 05:14