2010-07-05 230 views
2

我正在嘗試使用WPFToolkit的DataGrid控件(和C#/ .Net 3.5)來顯示每個記錄的ComboBox。隨着下面的代碼中,組合框出現,但其下拉列表包含項目:綁定DataGridComboBoxColumn ItemsSource到RelativeSource FindAncestor不起作用

<wpftkit:DataGrid ItemsSource="{Binding TransactionToEdit.SisterTransactions}" 
      AutoGenerateColumns="False"> 
<wpftkit:DataGrid.Columns> 
    <wpftkit:DataGridComboBoxColumn Header="Account" ItemsSource="{Binding RelativeSource={RelativeSource AncestorType={x:Type StackPanel}, diagnostics:PresentationTraceSources.TraceLevel=High}, Path=DataContext.Accounts}" DisplayMemberPath="Name"/> 
</wpftkit:DataGrid.Columns> 
</wpftkit:DataGrid> 

此外,Visual Studio的輸出窗口顯示以下錯誤:

System.Windows.Data Error: 4 : Cannot find source for binding with 
    reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.StackPanel', AncestorLevel='1''. 
    BindingExpression:Path=DataContext.Accounts; DataItem=null; target element is 
    'DataGridComboBoxColumn' (HashCode=25733404); target property is 
    'ItemsSource' (type 'IEnumerable') 

但是,下面的代碼工作預期(該組合框下拉列表中正確填寫):

<ItemsControl ItemsSource="{Binding TransactionToEdit.SisterTransactions}"> 
<ItemsControl.ItemTemplate> 
    <DataTemplate> 
    <ComboBox ItemsSource="{Binding RelativeSource={RelativeSource AncestorType={x:Type StackPanel}}, Path=DataContext.Accounts, diagnostics:PresentationTraceSources.TraceLevel=High}" DisplayMemberPath="Name"/> 
    </DataTemplate> 
</ItemsControl.ItemTemplate> 
</ItemsControl> 

注意,無論是DataGrid和ItemsControl的具有相同的ItemsSource字符串。所以做DataGridComboBoxColumn和ComboBox。一個控件正確綁定,另一個控件不正確。

爲什麼DataGridComboBoxColumn ItemsSource不能正確綁定?

謝謝

僅供參考,diagnostics被定義爲xmlns:diagnostics="clr-namespace:System.Diagnostics;assembly=WindowsBase"

+0

我有同樣的問題! DataGridComboBoxColumn只是一個損壞的東西! – Shimmy 2010-07-15 12:46:05

回答

3

有趣...如果我創建一個包含組合框的自定義的DataGridColumn,並使用相同的ItemsSource綁定字符串上面給出, 有用。

<wpftkit:DataGridTemplateColumn.CellTemplate> 
    <DataTemplate> 
    <ComboBox SelectedItem="{Binding Account}" ItemsSource="{Binding RelativeSource={RelativeSource AncestorType={x:Type StackPanel}}, Path=DataContext.Accounts}"  DisplayMemberPath="Name" /> 
    </DataTemplate> 
</wpftkit:DataGridTemplateColumn.CellTemplate> 
+1

我發現,如果我把組合框放在CellTemplate中,奇怪的事情可能會發生......比如當行切換到編輯模式時ComboBox會丟失它的選定值。一個簡單的解決方法是讓CellTemplate顯示一個TextBlock,然後將ComboBox放入CellEditingTemplate中。 – 2010-07-09 15:02:08

+1

這是一個bug,它已被提出 – 2010-09-05 13:04:10

相關問題