MVVM 轻量级 Silverlight 多项选择列表框在页面加载时进行初始选择

本文关键字:选择 加载 Silverlight 轻量级 列表 MVVM | 更新日期: 2023-09-27 18:36:23

我正在使用 MVVM 灯,并且有一个带有多项选择的列表框。在我的主页.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);
}

这工作正常并绑定到我的主视图模型。但是当页面加载时,我希望默认情况下选择集合项的第一项。请让我知道如何实现这一点

MVVM 轻量级 Silverlight 多项选择列表框在页面加载时进行初始选择

我建议使用 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 事件,则需要在模型中创建另一个属性,该属性将保存要选择的项,然后将该属性分配给ListBoxSelectedItem 属性。

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}"/>

通过拥有保存当前选定项的另一个属性,只要用户更改了所选项,您也可以在模型中访问该项。