MVVM指示灯Silverlight多个选择列表框初始选择页面加载

时间:2012-06-05 19:50:12

标签: c# silverlight list mvvm-light

我正在使用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。但是当加载页面时,我希望默认选择集合项的第一项。请让我知道如何实现这个

1 个答案:

答案 0 :(得分: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}"/>

通过拥有另一个保存当前所选项目的属性,无论何时用户更改所选项目,您还可以在模型中访问该项目。