質問の要点は以下のとおりです。
- WPFでListBoxにID(int型)のリストをバインドしている。しかしListBoxにはIDそのものではなくIDの指すインスタンスの名前を表示したい。何かいい方法はないだろうか。
- IDの指し示すデータはViewModelに用意されている。別の場所へ移しても構わない。
次のコードは、WPFでIDのリストにIDを追加していくことのできるアプリケーション コードの一部です。いま私が直面している問題を単純にしたものとなります。
lang
1class Hoge 2{ 3 public int Id { get; set; } 4 public string Name { get; set; } 5 6 public Hoge(int id, string name) 7 { 8 Id = id; 9 Name = name; 10 } 11} 12 13class ViewModel 14{ 15 // IDリスト 16 public ObservableCollection<int> ObjectIds { get; set; } 17 18 // IDの指すインスタンスのリスト 19 public ObservableCollection<Hoge> AvailableHoges { get; set; } 20 21 #region AddCommand 22 23 private void AddCommandHandler(object parameter) 24 { 25 ObjectIds.Add((int)parameter); 26 } 27 28 public ICommand AddCommand 29 { 30 get 31 { 32 if(_AddCommand == null) 33 _AddCommand = new DelegateCommand { CommandHandler = this.AddCommandHandler }; 34 return _AddCommand; 35 } 36 } 37 private ICommand _AddCommand; 38 39 #endregion 40 41 public ViewModel() 42 { 43 AvailableHoges = new ObservableCollection<Hoge>() 44 { 45 new Hoge(1, "Foo"), 46 new Hoge(2, "Bar"), 47 new Hoge(3, "Fizz"), 48 }; 49 ObjectIds = new ObservableCollection<int>(); 50 } 51}
このViewModelを次のXAMLコードにバインディングしています。
lang
1<Window x:Class="IdBinding.MainWindow" 2 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 3 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 4 Title="MainWindow" Height="350" Width="525"> 5 <StackPanel> 6 <ListBox ItemsSource="{Binding ObjectIds}" Height="100"/> 7 <ComboBox ItemsSource="{Binding AvailableHoges}" 8 Name="combo" 9 DisplayMemberPath="Name" 10 SelectedValuePath="Id"/> 11 <Button Content="追加" 12 Command="{Binding AddCommand}" 13 CommandParameter="{Binding SelectedValue, ElementName=combo}"/> 14 </StackPanel> 15</Window>
ComboBoxで選択しているHogeクラスのインスタンスのIdが、追加ボタンを押した時にListBoxにバインディングされているリストに追加される仕組みになっています。このままだとListBoxには追加されたIdの数字が表示されるのですが、今回はIdが指すAvailableHoge中のHogeクラスのNameを代わりに表示したいと思っています。期待する結果としては、この例ならリストに「1,1,2,3」と表示する代わりに「Foo,Foo,Bar,Fizz」と表示されるようにしたいと思っています。
この例ではListBoxにバインドされているObjectIdsをHogeクラスのリストに変更することでも解決するのですが、今直面している実際の問題ではObjectIdsの型を変更することが難しいため、別の方法を探しています。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。