2

이것은 내 첫 WPF 프로젝트이므로 나와 함께 맨발로하십시오. 여기 DataGrid CollectionViewSources를 정렬하기 위해 WPF ListCollectionView를 만드는 방법

내 CollectionViewSources 있습니다

<CollectionViewSource x:Key="topLevelAssysViewSource" d:DesignSource="{d:DesignInstance my:TopLevelAssy, CreateList=True}" /> 
<CollectionViewSource x:Key="topLevelAssysRefPartNumsViewSource" Source="{Binding Path=RefPartNums, Source={StaticResource topLevelAssysViewSource}}" /> 
<CollectionViewSource x:Key="topLevelAssysRefPartNumsRefPartNumBomsViewSource" Source="{Binding Path=RefPartNumBoms, Source={StaticResource topLevelAssysRefPartNumsViewSource}}" /> 

나는 현재 서로 데이터를 공급하는 다음과 같은 컨트롤이 있습니다

의 DataContext 내 창을 내 컨트롤의 모든 그리드 하우징을 통해 공급을 위해 :

<Grid DataContext="{StaticResource topLevelAssysViewSource}"> 

콤보 박스 :

<ComboBox DisplayMemberPath="TopLevelAssyNum" Height="23" HorizontalAlignment="Left" ItemsSource="{Binding}" Margin="12,12,0,0" Name="topLevelAssysComboBox" SelectedValuePath="TopLevelAssyID" VerticalAlignment="Top" Width="120" /> 
,451,515,

목록 상자가 :

<ListBox DisplayMemberPath="RefPartNum1" Height="744" HorizontalAlignment="Left" ItemsSource="{Binding Source={StaticResource topLevelAssysRefPartNumsViewSource}}" Margin="12,41,0,0" Name="refPartNumsListBox" SelectedValuePath="RefPartNumID" VerticalAlignment="Top" Width="120" /> 

마지막으로, 정렬-수 있도록 노력하고 데이터 그리드 : (지금은 그냥 하나 개의 칼럼) :

<DataGrid CanUserSortColumns="true" AutoGenerateColumns="False" EnableRowVirtualization="True" HorizontalAlignment="Left" ItemsSource="{Binding Source={StaticResource topLevelAssysRefPartNumsRefPartNumBomsViewSource}}" Margin="6,6,0,1" Name="refPartNumBomsDataGrid" RowDetailsVisibilityMode="VisibleWhenSelected" Width="707"> 
    <DataGrid.Columns > 
     <DataGridTextColumn x:Name="cageCodeColumn" Binding="{Binding Path=CageCode}" Header="CageCode" Width="45" /> 
     <DataGridTextColumn x:Name="partNumColumn" Binding="{Binding Path=PartNum}" Header="PartNum" Width="165" SortDirection="Ascending" /> 
    </DataGrid.Columns> 
</DataGrid> 

내 정확한 코드는 지금까지 있습니다 :

public partial class MainWindow : Window 
{ 
    racr_dbEntities racr_dbEntities = new racr_dbEntities(); 

    public MainWindow() 
    { 
     InitializeComponent(); 
    } 

    private System.Data.Objects.ObjectQuery<TopLevelAssy> GetTopLevelAssysQuery(racr_dbEntities racr_dbEntities) 
    { 
     // Auto generated code 

     System.Data.Objects.ObjectQuery<racr_dbInterface.TopLevelAssy> topLevelAssysQuery = racr_dbEntities.TopLevelAssys; 
     // Update the query to include RefPartNums data in TopLevelAssys. You can modify this code as needed. 
     topLevelAssysQuery = topLevelAssysQuery.Include("RefPartNums"); 
     // Update the query to include RefPartNumBoms data in TopLevelAssys. You can modify this code as needed. 
     topLevelAssysQuery = topLevelAssysQuery.Include("RefPartNums.RefPartNumBoms"); 
     // Returns an ObjectQuery. 
     return topLevelAssysQuery; 
    } 

    private void Window_Loaded(object sender, RoutedEventArgs e) 
    { 
     // Load data into TopLevelAssys. You can modify this code as needed. 
     CollectionViewSource topLevelAssysViewSource = ((CollectionViewSource)(this.FindResource("topLevelAssysViewSource"))); 
     ObjectQuery<racr_dbInterface.TopLevelAssy> topLevelAssysQuery = this.GetTopLevelAssysQuery(racr_dbEntities); 
     topLevelAssysViewSource.Source = topLevelAssysQuery.Execute(MergeOption.AppendOnly); 

     ListCollectionView topLevelAssyView = CollectionViewSource.GetDefaultView(CollectionViewSource.CollectionViewTypeProperty) as ListCollectionView; 
     topLevelAssyView.SortDescriptions.Add(new SortDescription("PartNum", ListSortDirection.Descending)); 
    } 

나는 CollectionViewS에 포함 된 정렬 속성을 처리하기 위해 ListCollectionViews를 만드는 것이 중요하다는 것을 읽고 이해했습니다. ource, 나는 blog에서 얻었습니다 Bea Stollnitz's blog.

그러나 Null 참조 예외 처리되지 않은 오류 메시지가 계속 발생합니다. "개체 참조가 개체의 인스턴스로 설정되지 않았습니다."

이 문제는 어떻게 처리합니까? ListCollectionView를 더 정의해야합니까, 아니면 ICollectionView를 설정해야합니까? 내 PartNum 열에는 숫자와 때로는 문자로 시작하는 부품 번호가 들어 있습니다. 표준 sortdirections가 적용됩니까?

답변

0

예외에 대해 전체 스택 추적을 제공하거나이 예외를 throw하는 예제의 행 번호를 제공하십시오. 지금까지 제공 한 것과

, 난 당신이 엔티티 프레임 워크, ListCollectionView를, 따라서 NullReferenceException이되지 않습니다하여 ObjectQuery 결과에 대한 기본보기를 사용하는 경우 오류의 원인이

ListCollectionView topLevelAssyView = CollectionViewSource.GetDefaultView(CollectionViewSource.CollectionViewTypeProperty) as ListCollectionView; 

을 생각합니다.

ObjectQuery/EntityCollection을 CollectionViewSource의 소스로 사용하고 정렬하려면 정렬을 지원하는 다른 컨테이너로 래핑해야합니다 (CRUD를 수행하려면 소스 EntityCollection 대신 해당 컨테이너를 사용하십시오).

ObservableCollection<TopLevelAssy> observableCollection = new ObservableCollection(topLevelAssysQuery.Execute(MergeOption.AppendOnly)); 
((ISupportInitialize)topLevelAssysViewSource).BeginInit(); 
topLevelAssysViewSource.CollectionViewType = typeof(ListCollectionView); 
topLevelAssysViewSource.Source = observableCollection; 
topLevelAssysViewSource.SortDescriptions.Add(new SortDescription("CageCode", ListSortDirection.Ascending)); 
((ISupportInitialize)topLevelAssysViewSource).EndInit(); 

을 그리고 당신이 CollectionViewSource.View의 속성을 참조 바인딩 변경 :

예를 들어, 그 라인을 따라 뭔가를 시도

ItemsSource="{Binding Source={StaticResource topLevelAssysViewSource}, Path=View}" 

추가 독서 과제 : http://blog.nicktown.info/2008/12/10/using-a-collectionviewsource-to-display-a-sorted-entitycollection.aspx

+0

응답 해 주셔서 감사합니다 , Surfen - 정말 고맙습니다.오류 메시지가 ListCollectionView가 정의 된 행에 표시된다는 점에서 옳습니다. ObservableCollection을 만들고 내 ItemsSource를 변경하려고했으나 머리가 약간 뒤져서 편집 된 코드를 성공적으로 실행할 수 없었습니다. 나는 당신이 말한 것을 복습하고 나의 질문에 대해보다 통찰력있는 재 게시를하려고 노력할 것입니다. –

+0

반갑습니다. BTW, 확실하지 않은 경우 XAML로 인스턴스화 한 후 CollectionViewType을 변경할 수 있으므로이 할당을 XAML로 옮길 수 있습니다. 하지만 CollectionViewSources에 다른 문제가있어서 결국에는 코드를 작성하고 유지 관리해야했습니다. – surfen

+0

흠 ... 아직 해결책이 없습니다. 정말 1. 필자의 collectionViewSources에 observablesCollection을 설정하거나, 2. ICollectionView를 만듭니다. 이것은 실제로 구현되기보다 구현하기가 더 쉬워 보였습니다. –