2010-01-28 2 views
1

IQueryable에서 파생 된 ObservableCollection에 바인딩 된 ListView가 있습니다. 컬렉션을 새로 고치면 항목이 추가되거나 편집되거나 버튼이 클릭됩니다 (데이터베이스에 다른 사용자가있는 새 항목이 있는지 확인하기 위해). 목록 상자가 새로 고쳐지고 컬렉션의 첫 번째 항목이 선택됩니다.바인딩 된 컬렉션을 새로 고칠 때 ListView에서 동일한 항목을 유지하십시오.

새로 고침 후에 동일한 선택된 항목을 유지하려고하지만 (여전히 존재하는 경우) 컬렉션이 대체되었으므로 이전 컬렉션의 항목과 새 항목의 동일성을 비교할 수 없습니다. 모든 attemtps는 절대로 일치하지 않습니다.

어떻게해야합니까? 누군가가 그들을보고 싶어 경우 아래

는 몇 가지 관련 코드 snipets 있습니다

목록보기는 MouseDoubleClick 이벤트는 편집 창을 엽니 다

<ListView x:Name="IssueListView" 
      ItemsSource="{Binding Issues}" 
      ItemTemplate="{StaticResource ShowIssueDetail}" 
      IsSynchronizedWithCurrentItem="True" 
      MouseDoubleClick="IssueListView_MouseDoubleClick" /> 

는 문제 모음입니다 DataTemplate을

<DataTemplate x:Key="ShowIssueDetail"> 
    <Border CornerRadius="3" Margin="2" MinWidth="400" BorderThickness="2" 
     BorderBrush="{Binding Path=IssUrgency, 
        Converter={StaticResource IntToRYGBBorderBrushConverter}}"> 
      <StackPanel Orientation="Vertical"> 
      <TextBlock Text="{Binding Path=IssSubject}" 
         Margin="3" FontWeight="Bold" FontSize="14"/> 

      <!--DataTrigger will collapse following panel for simple view--> 
      <StackPanel Name="IssueDetailPanel" Visibility="Visible" Margin="3"> 
      <StackPanel Width="Auto" Orientation="Horizontal"> 
       <TextBlock Text="Due: " FontWeight="Bold"/> 
       <TextBlock Text="{Binding Path=IssDueDate, StringFormat='d'}" 
         FontStyle="Italic" HorizontalAlignment="Left"/> 
      </StackPanel> 
      <StackPanel Width="Auto" Orientation="Horizontal"> 
       <TextBlock Text="Category: " FontWeight="Bold"/> 
       <TextBlock Text="{Binding Path=IssCategory}"/> 
      </StackPanel> 
      </StackPanel> 

     </StackPanel> 
     </Border> 

     <DataTemplate.Triggers> 
      <DataTrigger Binding="{Binding Path=StatusBoardViewModel.ShowDetailListItems, 
         RelativeSource={RelativeSource FindAncestor, 
         AncestorType={x:Type Window}}}" Value="False"> 
       <Setter TargetName="IssueDetailPanel" 
         Property="Visibility" Value="Collapsed"/> 
      </DataTrigger> 
     </DataTemplate.Triggers> 
    </DataTemplate> 

입니다 바운드 컨트롤을 기반으로 프로그래밍 방식으로 Linq To SQL 쿼리를 작성하는 QueryIssues 메서드를 실행하여 새로 고칩니다. IssuesQuery는

나는 작은 뷰 모델 클래스에 표시 할 항목을 감쌌다 과거에이 문제에 직면
public void QueryIssues() 
{ 
    // Will show all items 
    IssuesQuery = from i in db.Issues 
      orderby i.IssDueDate, i.IssUrgency 
      select i; 

    // Filters out closed issues if they are not to be shown 
    if (includeClosedIssues == false) 
    { 
     IssuesQuery = from i in IssuesQuery 
       where i.IssIsClosed == false 
       select i; 
    } 

    // Filters out Regular Tasks if they are not to be shown 
    if (showTasks == false) 
    { 
     IssuesQuery = from i in IssuesQuery 
       where i.IssIsOnStatusBoard == true 
       select i; 
    } 

    // Filters out private items if they are not to be shown 
    if (showPrivateIssues == false) 
    { 
     IssuesQuery = from i in IssuesQuery 
       where i.IssIsPrivate == false 
       select i; 
    } 

    // Filters out Deaprtments if one is selected 
    if (departmentToShow != "All") 
    { 
     IssuesQuery = from i in IssuesQuery 
       where i.IssDepartment == departmentToShow 
       select i; 
    } 

    Issues = new ObservableCollection<Issue>(IssuesQuery); 
} 

답변

0

는, 각 여분의 재산에 isSelected 주어진 다음에이 속성을 바인드 된 IQueryable 속성입니다 ItemContainerStyle을 사용하는 ListBoxItem입니다. 그렇게하면 내가 선택한 것을 추적 할 수 있습니다.

+0

내가 따라 확실하지 않다. CollectionViewSource가 바뀌면 선택한 개체가 사라집니다. 새 목록의 모든 항목을 반복하여 일치 항목을 찾을 수 있도록 선택한 항목에 대한 충분한 정보를 유지해야한다고 말하는 것입니까? 나는 더 깨끗한 해결책을 원했다. –

1

완전히 새로운 객체를 얻었 기 때문에 기존 객체와 일치하는 항목을 찾고 선택하는 것보다 평등과 일치하는 다른 방법이 없습니다. 컬렉션을 교체하면 선택한 항목을 직접 추적해야합니다.

다른 옵션 : 당신은 컬렉션을 유지하고 수동으로 추가/쿼리 결과에 따라 항목을 제거 할 수

(즉, 현재의 아이템을 파괴하지 않습니다).

1

한 가지 방법은 뷰 모델에서이 작업을 수행합니다 :

// The ListView's SelectedItem is bound to CurrentlySelectedItem 
var selectedItem = this.CurrentlySelectedItem; 

// ListView is bound to the Collection property 
// setting Collection automatically raises an INotifyPropertyChanged notification 
this.Collection = GetIssues(); // load collection with new data 

this.CurrentlySelectedItem = this.Collection.SingleOrDefault<Issue>(x => x.Id == selectedItem.Id); 
+0

다음은이 주제에 대한 블로그 게시물입니다. http://bengribaudo.com/blog/2010/09/14/199/keeping-selected-item-selected-when-changing-listviews-itemssource –

관련 문제