2013-05-24 1 views
1

LINQ를 처음 사용했습니다. WPF를 사용하여 프로젝트에서 사용하고 싶습니다. 각 wpf 페이지 (ListBox1 첫 wpf 페이지 및 ListBox2 두 번째 wpf 페이지)에 대해 두 listBoxes 있습니다. ListBox1에서 ListBox2로 선택된 값을 전달해야합니다. wpf listbox를 사용하여 LINQ를 사용하여 선택된 값 가져 오기

첫 WPF 페이지

:
private void btnNext_Click(object sender, RoutedEventArgs e) 
    { 
      List<FoodInformation> _dinners = (from ListItem item in ListOfFood.Items 
              where item.selecteditem select item).ToList(); 

      //(above: this linq - item.SelectedItems doesnt work. How?) 

      var passValue = new ScheduleOperation(_dinners); 

      Switcher.Switch(passValue); //go to another page 
    } 

두 번째 WPF 페이지에 ListBox1

: ListBox2는

public ScheduleOperation(List<FoodInformation> items) 
     : this() 
    { 
     valueFromSelectionOperation = items; 
     ListOfSelectedDinners.ItemsSource ; 
     ListOfSelectedDinners.DisplayMemberPath = "Dinner"; 
    } 

는 코딩과 당신의 도움은 매우 극명하게 될 것이다. 감사!

+0

ListBox에는 SelectedItems 속성이 있는데, LINQ가 필요하지 않다는 것을 알고 계십니까? –

답변

0

은 귀하의 질문에 대한 내 댓글 이외에, 당신은 같은 것을 할 수 있습니다

 var selectedFromProperty = ListBox1.SelectedItems; 
     var selectedByLinq = ListBox1.Items.Cast<ListBoxItem>().Where(x=>x.IsSelected); 

그냥 확인 목록 상자에서 모든 항목이 ListBoxItem의 유형인지 확인하십시오.

후세를 위해서
0

... 일반적으로

, 당신은 IEnumerable을 필요 LINQ 뭔가를 사용할 수 있습니다. Items는 ItemCollection이고 SelectedItems는 SelectedItemCollection입니다. 그들은 IEnumerable은 아니지만 IEnumerable을 구현합니다. 이것은 모든 종류의 다른 것들을 하나의 ListBox에 집어 넣을 수있게합니다.

명시 적으로 ListBoxItems를 목록에 넣지 않으면 실제로 목록에 넣은 항목의 유형으로 캐스트해야합니다. 그것이 가능하지만

var selectedFromProperty = ListBox1.SelectedItems.Cast<string>(); 

이 얻을 :

<ListBox Height="200" SelectionMode="Multiple" x:Name="ListBox1"> 
    <system:String>1</system:String> 
    <system:String>2</system:String> 
    <system:String>3</system:String> 
    <system:String>4</system:String> 
</ListBox> 

또는 C#을 사용하여 : randomListBox.ItemsSource = new List<string> {"1", "2", "3", "4"};

ListBox1.SelectedItems 문자열로 캐스트 할 필요가 예를 들어

, 문자열은 XAML을 사용하여 ListBoxItem (여기에서 설명 됨 : Get the ListBoxItem in a ListBox)을 찾아야하기 때문에 Items에서 선택한 항목을 가져올 수 있습니다. 당신은 여전히 ​​그것을 할 수는 있지만 그것을 권장합니다.

var selectedByLinq = ListBox1.Items 
    .Cast<string>() 
    .Select(s => Tuple.Create(s, ListBox1.ItemContainerGenerator 
     .ContainerFromItem(s) as ListBoxItem)) 
    .Where(t => t.Item2.IsSelected) 
    .Select(t => t.Item1); 

ListBox의 기본값은 가상화이므로 ContainerFromItem은 null을 반환 할 수 있습니다.

관련 문제