WPF ListBox Multi-selection Binding (2)

  • 72
  • 0

前一篇介紹過簡單的單向處理,這一篇討論雙向繫結的情況。

雙向繫結處理,View Model 的變化也要反映到 UI

這個做法的第一步是要讓 PersonViewModel 能夠辨識自己是否有被選擇,所以我們加上一個 IsSelected 的屬性:

 public class PersonViewModel : NotifyPropertyBase
 {
     private int _age;
     public int Age
     {
         get { return _age; }

         set { SetProperty(ref _age, value); }
     }
     private string _name;
     public string Name
     {
         get { return _name; }
         set { SetProperty(ref _name, value); }
     }

     private string _city;

     public string City
     {
         get { return _city; }
         set { SetProperty(ref _city, value); }
     }

     private bool _isSelected;
     public bool IsSelected
     {
         get { return _isSelected; }
         set { SetProperty(ref _isSelected, value); }
     }
    
 }

這時候要讓 ListBoxItem 的 IsSelected 屬性繫結到 PersonViewModel 上的 IsSelected,所以在 XAML 上加上一個 ListBoxItem 的樣式設定:

 <ListBox.Resources >
     <Style TargetType="ListBoxItem" BasedOn="{StaticResource  {x:Type ListBoxItem}}">
         <Setter Property="IsSelected" Value="{Binding IsSelected}"/>
     </Style>
 </ListBox.Resources>

建立一個 ShowCommand 用於顯示被選擇的選項:

  private ICommand _showCommand;
  public ICommand ShowCommand
  {
      get
      {
          _showCommand = _showCommand ?? new RelayCommand((x) =>
          {
              var builder = new StringBuilder();

              foreach (var p in People.Where((y) => y.IsSelected))
              {
                  builder.AppendLine($"{p.Name} 是 {p.Age} 住在 {p.City}");
              }

              MessageBox.Show(builder.ToString());

          });
          return _showCommand;
      }
  }

為了測試雙向繫結,另外建立一個 ChangeCommand 來改變 index 0 資料的 IsSelected 屬性:

  private ICommand _changeCommand;
  public ICommand ChangeCommand
  {
      get
      {
          _changeCommand = _changeCommand ?? new RelayCommand((x) => People[0].IsSelected = !People[0].IsSelected);
          return _changeCommand;
      }
  }

完整範例請參考 ListBoxBindingSample002