2014-10-04 48 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")