2014-10-04 47 views
0

在我的XAML代碼我已經定義了一個CollectionViewSource作爲網格資源:找不到CollectionViewSource使用FindResource

<Grid.Resources> 
     <CollectionViewSource x:Key="AgentsViewSource" 
          Source="{StaticResource Agents}"> 
      <CollectionViewSource.SortDescriptions> 
       <componentModel:SortDescription PropertyName="ID" /> 
      </CollectionViewSource.SortDescriptions> 
     </CollectionViewSource> 
</Grid.Resources> 

再往下,作爲一個工具箱的孩子這又是網格我有一個孩子組合框應改變SortDescription

<ComboBox Name="SortOrderBox" ItemsSource="{Binding AvailableProperties}" SelectionChanged="newSortOrder_OnSelectionChanged" Width="130" FontSize="15"/> 

用下面的代碼背後:

private void newSortOrder_OnSelectionChanged(object sender, SelectionChangedEventArgs e) 
    { 
     var newSortOrder = (string) SortOrderBox.SelectedItem; 
     var sortDescription = new SortDescription(newSortOrder, ListSortDirection.Descending); 

     var source = (CollectionViewSource) FindResource("AgentsViewSource"); 

     source.SortDescriptions.Clear(); 
     source.SortDescriptions.Add(sortDescription); 
    } 

但是,當我嘗試使用FindResource時,我總是得到一個異常。我真的不知道我在做什麼錯誤,所以所有的輸入是讚賞。

回答

2

您正試圖在window/userControl資源下查找資源。在網格實例

設置x:Name對電網和調用FindResource,因爲它被聲明爲在網格中的資源,不是在窗口/用戶控件。

<Grid x:Name="grid"> 
    ..... 
</Grid> 

後面的代碼:

grid.FindResource("AgentViewSource")