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事件,那么您需要在模型中创建另一个属性来保存您想要选择的项目,然后将该属性分配SelectedItemListBox.

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 回答