2013-04-19 112 views
0

我正在創建一個使用MVVM光模式的Windows Phone應用程序。我在列表框中遇到問題,因爲它總是返回一個負值(-1)的選定索引。有誰知道如何解決它?ListBox索引返回負值

這是我在View Model中的代碼,我錯過了什麼?謝謝!

public void OnViewListSelectedItem(SelectionChangedEventArgs e) 
    { 

     ListBox lb = new ListBox(); 

     if (e.AddedItems.Count == 1) 
     { 
      if (lb.SelectedIndex == 0) 
      { 
       _navigationService.NavigateTo(new Uri(ViewModelLocator.ByVendorUrl, UriKind.Relative)); 
      } 

      if (lb.SelectedIndex == 1) 
       { 
        _navigationService.NavigateTo(new Uri(ViewModelLocator.ByVendorUrl, UriKind.Relative)); 
       } 
      if (lb.SelectedIndex == 2) 
       { 
        _navigationService.NavigateTo(new Uri(ViewModelLocator.ByCombinationUrl, UriKind.Relative)); 
       } 
      } 
    } 

XAML代碼這裏

<ListBox x:Name="lbviewlist"> 
       <i:Interaction.Triggers> 
         <i:EventTrigger EventName="SelectionChanged"> 
          <Command:EventToCommand Command="{Binding ViewListCommand}" PassEventArgsToCommand="True"/> 
         </i:EventTrigger> 
        </i:Interaction.Triggers> 
        <ListBox.Items> 
        <ListBoxItem Content="By Product" FontSize="35" Margin="10,12,12,0"/> 
        <ListBoxItem Content="By Vendor" FontSize="35" Margin="10,12,12,0"/> 
        <ListBoxItem Content="By Best Combination" FontSize="35" Margin="10,12,12,0"/> 
        </ListBox.Items> 
       </ListBox> 

回答

2

你創建你的代碼的新列表框()(稱爲磅)。你不填充它,所以這將是空的,總是會有-1

一個的SelectedIndex然後檢查「E」的「源」屬性,並將其轉換爲一個列表框

ListBox myList = (ListBox) e.Source; 

你然後可以訪問myList上的屬性。

+0

謝謝,我剛剛意識到它錯了,以創建新的列表框。但是,你知道我該如何檢查我的lblistview的選擇狀態? 我不知道如何從我的代碼訪問/ lblistview。唯一可用的是(e)。你可以幫我嗎?請。非常感謝 – JennyJane

+0

您在XAML中將其命名,因此您可以從其名稱訪問它(lbviewlist) 在Visual Studio中,只需輸入名稱和'。'即可。你會看到可用的屬性,事件和方法。 –

+0

因爲我不是從後面的代碼編寫代碼,所以我無法從它的名稱訪問它,我使用View Model代替。訪問它的唯一方法是通過我的方法ViewListCommand的(e)參數,它綁定到我的列表框的事件。但是,當我在我的ViewModel中直接鍵入(e)時,唯一可用的選項是上面我的代碼中顯示的AddedItems。 – JennyJane

1

根據我的研究,對於SelectedIndex屬性使用get訪問器時,listbox的SelectedIndex屬性不可綁定,它總是返回-1。嘗試對SelectedIndex屬性使用set訪問器會引發NotSupportedException。 - MSDN List selectedporperty

我也更新了我的代碼,因爲我的第一個代碼是錯誤的,它創建了新的列表框,結果爲空/空。另外selectionchanged事件沒有問題被用作事件。

public void method (SelectionChangedEventArgs e) 
    { 


     {     
      if (e.AddedItems.Count == 1) 
      { 
       var listBoxItem = (ListBoxItem)e.AddedItems[0]; 
       string _string1 = "Test"; 
       if ((string)listBoxItem.Content == _string1) 
       { 
        navigationService.NavigateTo(new Uri(ViewModelLocator.page1, UriKind.Relative)); 
       } 
      } 
     } 
} 

那就是它。希望能幫助到你! :)