2012-06-05 36 views
1

我正在使用MVVM指示燈並且有多個選擇的列表框。在我的Mainpage.xaml我有MVVM light Silverlight multiple頁面加載時的選擇列表框初始選擇

<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。但是當頁面加載時,我希望默認情況下選擇收集項目的第一項。請讓我知道如何實現這個

回答

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事件,那麼您將需要在模型中創建另一個屬性,該屬性將包含要選擇的項目,然後將該屬性分配給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}"/> 

通過具有保持當前所選項目的另一個屬性,你也有你的模型,以該項目接入以及時所選擇的項目是由用戶更改。

+0

什麼是MyList_SelectionChanged。假設ListBox1_SelectionChanged當我嘗試在行ListBox1.SelectedIndex = 0;我得到「ArgumentOutOfRange異常」因爲ListBox1的ItemsSource尚未加載 –

+0

錯誤是因爲綁定尚未發生;看看我的編輯使用更多的MVVM方法,使用另一個屬性來保存'ListBox'中的當前選定項。 –

+0

很酷的工作.....感謝您幫助我 –

相關問題