2011-03-23 89 views
2

是否有某種方法可以使的DataContext在其資源中的綁定中使用?從DataTemplate中的資源進行綁定

<DataTemplate x:Key="History"> 
    <ItemsControl ItemsSource="{Binding History}"> 
    <ItemsControl.Resources> 
     <app:BitmapProvider x:Key="Converter" ShowDetails="True" 
          Type="{Binding Model.Type}" /> 
    </ItemsControl.Resources> 
    <ItemsControl.ItemsPanel> 
     <ItemsPanelTemplate> 
     <StackPanel Orientation="Horizontal" IsItemsHost="True"/> 
     </ItemsPanelTemplate> 
    </ItemsControl.ItemsPanel> 
    <ItemsControl.ItemTemplate> 
     <DataTemplate> 
     <Image Source="{Binding Data, Converter={StaticResource Converter}}" /> 
     </DataTemplate> 
    </ItemsControl.ItemTemplate> 
    </ItemsControl> 
</DataTemplate> 

上述模板被用作ListBoxCellTemplate。該級別的對象有兩個屬性,History(包含「歷史信息」對象列表)和Model(包含一堆其他內容,包括Type)。我正在使用ItemsControl來顯示彼此相鄰的歷史項目;我想爲每個圖像顯示一張圖像,圖像是從BitmapProvider獲得的,這是一個IValueConverter

轉換器需要兩位信息來獲得結果:一個是各個歷史項目的Data,另一個是整個集合的Type。另外一個複雜的情況是,構建這個特定的轉換器(或者改變給它的Type)是昂貴的,所以我不想把它放在個別歷史項目的層面上,或者使用MultiBinding,而且我不能將它放在模板之外,因爲那樣它將無法訪問Type

不幸的是,上面給了我以下錯誤:

System.Windows.Data錯誤:2:無法找到目標元素理事FrameworkElement的或FrameworkContentElement上。 BindingExpression:路徑= Model.Type;的DataItem = NULL;目標元素是'BitmapProvider'(HashCode = 57142809);目標屬性是'Type'(類型'TypeDetails')

我的理解是指資源無法弄清楚如何獲取它所包含的元素的DataContext。 (我已經搜索過了,大部分我能找到的答案都建議將它移動到模板之外或使用MultiBinding代替 - 在我的例子中,這兩種方法都不能真正起作用,但我會很高興被證明是錯誤的,或給出另一種選擇。)

回答

3

我認爲你可以用DataContextSpy來完成。

嘗試類似:

<ItemsControl.Resources> 
    <spy:DataContextSpy x:Key="Spy"/> 
    <app:BitmapProvider x:Key="Converter" ShowDetails="True" 
         Type="{Binding DataContext.Model.Type,Source={StaticResource Spy}}" /> 
</ItemsControl.Resources> 
+0

+1的DataContextSpy,我在這裏學到的東西... – David 2011-03-23 08:56:27

+0

這是新的我了。但它的工作。謝謝! (我仍然在考慮一種不同的解決方案:將昂貴的部件提取到由集合的ViewModel託管的單獨的類中,並使轉換器使用該項目和該項目的Data來獲得結果。但我不那麼喜歡它,因爲它感覺太像使用View-specific數據污染ViewModel - 我喜歡能夠在多個Views之間共享一個ViewModel。) – Miral 2011-03-24 04:53:43

+0

不要擔心這是一種破解!如果你看那篇文章的日期(2008年7月),你會發現它已經存在了一段時間。另一個非常有用的類是[ElementSpy](http://joshsmithonwpf.wordpress.com/2008/07/22/enable-elementname-bindings-with-elementspy/)。將它保留在有用的WPF幫助程序列表中! – 2011-03-24 08:45:00