こんにちは。WPFを勉強中の者です。
###前提・実現したいこと
ViewのListBoxで選択している項目をViewModelに通知する方法を知りたいです。
###発生している問題・エラーメッセージ
簡単な例として、ViewModelにあるコレクションをリストボックスにバインディングして、画面下部にあるボタンを押すとリストボックス上で選択している要素をコレクションから削除するというシステムを考えています。
現段階でボタンを押したらコレクションの先頭の要素を削除する機能は実現できています。選択中のListBoxの項目番号をViewModelに通知することが出来れば任意の要素をコレクションから削除することが出来ると考えています。
以下に自分で作ったソースを置きます。
何卒よろしくお願いいたします。
###該当のソースコード
ListAddRemoveViewプロジェクト MainWindow.xaml ------------------------------------------ <Window x:Class="ListAddRemoveView.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="*" /> <RowDefinition Height="20" /> </Grid.RowDefinitions> <ListBox Name="listbox" Grid.Column="0" ItemsSource="{Binding}"> <ListBox.ItemTemplate> <HierarchicalDataTemplate> <TextBlock Text="{Binding Name}" /> </HierarchicalDataTemplate> </ListBox.ItemTemplate> </ListBox> <Button Name="button" Content="RemoveButton" Grid.Row="1" Command="{Binding RemoveElement}" /> </Grid> </Window> MainWindow.xaml.cs --------------------------------------- using System.Windows; using ListAddRemoveViewModel; namespace ListAddRemoveView { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); this.DataContext = new MainWindowViewModel(); } } } ListAddRemoveViewModelプロジェクト MainWindowViewModel.cs -------------------------------------------- using System.Collections.ObjectModel; using System.Windows.Input; using Microsoft.Practices.Prism.Commands; namespace ListAddRemoveViewModel { public class MainWindowViewModel :ObservableCollection<Person> { public MainWindowViewModel() { Add(new Person { Name = "Human01" }); Add(new Person { Name = "Human02" }); Add(new Person { Name = "Human03" }); Add(new Person { Name = "Human04" }); Add(new Person { Name = "Human05" }); } private ICommand removeElement; public ICommand RemoveElement { get { return removeElement = new DelegateCommand(removeMethod); } } private void removeMethod() { RemoveAt(0); } } public class Person { private string name; public string Name { get { return name; } set { name = value; } } } }
###補足情報(言語/FW/ツール等のバージョンなど)
言語 C#
開発環境 Visual Studio 2013
Microsoft .NETFramework 4.6.1

回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/03/13 11:16
2017/03/13 11:29
2017/03/14 03:02