1

MVVM ライトを使用しており、複数選択できるリスト ボックスがあります。私のMainpage.xamlには

<ListBox Name="ListBox1" ItemsSource="{Binding Items}" Grid.Column="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Background="Transparent"  Margin="15,15,18,0" SelectionMode="Multiple" Height="100" />

MainPage.xaml.cs にはあります (何らかの理由で依存関係プロパティを使用したくありません)。

MainPage()
{
    ListBox1.SelectionChanged = new SelectionChangedEventHandler(ListBox1_SelectionChanged);
}

void ListBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
 var listBox = sender as ListBox;
 var viewModel = listBox.DataContext as MainViewModel;
 viewModel.SelectedItems.Clear();
 foreach (string item in listBox.SelectedItems)
     viewModel.SelectedItems.Add(item);
}

これは正常に機能し、MainViewModel にバインドします。しかし、ページが読み込まれると、コレクション項目の最初の項目がデフォルトで選択されます。これを実装する方法を教えてください

4

1 に答える 1

0

ListBox のLoadedイベントを使用してから、コレクションの最初の項目にバインドすることをお勧めします。

MainPage()
{
    ListBox1.Loaded += new RoutedEventHandler( OnListBox1Loaded );
    ListBox1.SelectionChanged += new SelectionChangedEventHandler(ListBox1_SelectionChanged);
}

private void OnListBox1Loaded( object sender, RoutedEventArgs e )
{
    // make sure the selection changed event doesn't fire
    // when the selection changes
    ListBox1.SelectionChanged -= MyList_SelectionChanged;

    ListBox1.SelectedIndex = 0;
    e.Handled = true;

    // re-hook up the selection changed event.
    ListBox1.SelectionChanged += MyList_SelectionChanged;
}

編集

イベントを使用できない場合は、Loaded選択したいアイテムを保持するモデルに別のプロパティを作成し、そのプロパティを のSelectedItemプロパティに割り当てる必要がありListBoxます。

public class MyModel : INotifyPropertyChanged
{

  private ObservableCollection<SomeObject> _items;
  public ObservableCollection<SomeObject> Items
  {
    get { return _items; }
    set
    {
        _items = value;
        NotifyPropertyChanged( "Items" );
    }
  }

  private SomeObject _selected;
  public SomeObject  Selected
  {
    get { return _selected; }
    set
    {
        _selected = value;
        NotifyPropertyChanged( "Selected" );
    }
  }

  public void SomeMethodThatPopulatesItems()
  {
    // create/populate the Items collection

    Selected = Items[0];
  }

  // Implementation of INotifyPropertyChanged excluded for brevity

}

XAML

<ListBox ItemsSource="{Binding Path=Items}" 
         SelectedItem="{Binding Path=Selected}"/>

現在選択されている項目を保持する別のプロパティを持つことで、選択された項目がユーザーによって変更されるたびに、モデルでその項目にもアクセスできます。

于 2012-06-05T20:10:52.297 に答える