2013-04-19 5 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

당신은 당신의 코드에서 새로운 목록 상자 (()라는 파운드)를 만들 수 있습니다. 그런 다음 'E'의 '소스'속성을 확인하고 목록 상자에 캐스팅 비어있을 것입니다, 그래서 그것을 채우지 않고 항상 -1

에도 selectedIndex있을 것이다

ListBox myList = (ListBox) e.Source; 

당신에게 그런 다음 myList의 속성에 액세스 할 수 있습니다.

+0

감사합니다. 저는 방금 새 목록 상자를 만드는 것이 잘못되었음을 깨달았습니다. 그러나, 내 lblistview의 선택 상태를 어떻게 확인할 수 있습니까? 내 코드에서/lblistview에 액세스하는 방법을 모르겠습니다. 접근 할 수있는 유일한 것은 (e)입니다. 나 좀 도와 줄 수있어? 부디. 고마워요. – JennyJane

+0

XAML에서 이름을 지정 했으므로 이름 (lbviewlist)에서 액세스 할 수 있습니다. Visual Studio에서 이름을 입력하고 '.' 사용 가능한 속성, 이벤트 및 메서드가 표시됩니다. –

+0

코드 뒤에서 코딩하지 않기 때문에 이름에서 액세스 할 수 없으며 대신보기 모델을 사용하고 있습니다. 그것을 액세스하는 유일한 방법은 내 목록의 이벤트에 바인드 된 내 메소드 ViewListCommand의 thru (e) 매개 변수입니다. 그러나 글자 그대로 (e)를 ViewModel에 입력 할 때 위의 코드에서와 같이 AddedItems 옵션 만 사용할 수 있습니다. – JennyJane

1

목록 상자의 SelectedIndex 속성은 바인드 할 수 없으므로 SelectedIndex 속성에 get 접근자를 사용하면 항상 -1이 반환됩니다. SelectedIndex 속성에 대해 set 접근자를 사용하려고하면 NotSupportedException가 발생합니다. - MSDN List selectedporperty

내 첫 번째 코드가 잘못되어 새 목록 상자가 만들어지고 결과가 비어 있거나 null이되기 때문에 코드가 업데이트되었습니다. 또한 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)); 
       } 
      } 
     } 
} 

그 것이다. 희망이 도움이됩니다! :)