2011-08-13 43 views
4

我想數據綁定DataGridComboBoxColumnDataGridComboBoxColumn數據綁定

<DataGridComboBoxColumn Header="Number of Copies" SelectedItemBinding="{Binding NumberCopies}"> 
    <DataGridComboBoxColumn.ElementStyle> 
     <Style TargetType="ComboBox"> 
      <Setter Property="ItemsSource" Value="{Binding LifeAreaList}"/> 
      <Setter Property="IsReadOnly" Value="True"/> 
     </Style> 
    </DataGridComboBoxColumn.ElementStyle> 
</DataGridComboBoxColumn> 

我做錯了什麼在這裏,因爲我得到的運行時間空組合框。


我得到了以下

System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=LifeAreaList; DataItem=null; target element is 'DataGridComboBoxColumn' (HashCode=49475561); target property is 'ItemsSource' (type 'IEnumerable')

+0

在運行時會在輸出窗口中報告哪些錯誤? –

回答

6

DataGridColumn沒有得到來自FrameworkElementFrameworkContentElement所以它不是在視覺樹好好嘗試一下有DataContext,這就是爲什麼你的綁定失敗。

如果您綁定的List<int>對每個項目都是相同的,那麼也許您應該找到另一種綁定方式,也許可以將其設置爲靜態,並在綁定中使用StaticResource

無論如何,要將ItemsSource綁定到源類中的List<int>屬性,您可以使用ElementStyleElementEditingStyle(正如其他人指出的那樣)。以下內容應該可以工作

<DataGridComboBoxColumn Header="Number of Copies" 
         SelectedItemBinding="{Binding ListAreaItem}"> 
    <DataGridComboBoxColumn.ElementStyle> 
     <Style TargetType="ComboBox"> 
      <Setter Property="ItemsSource" Value="{Binding LifeAreaList}"/> 
     </Style> 
    </DataGridComboBoxColumn.ElementStyle> 
    <DataGridComboBoxColumn.EditingElementStyle> 
     <Style TargetType="ComboBox"> 
      <Setter Property="ItemsSource" Value="{Binding LifeAreaList}"/> 
     </Style> 
    </DataGridComboBoxColumn.EditingElementStyle> 
</DataGridComboBoxColumn> 
+0

,謝謝你的回答,看起來很有趣。如果我將我的清單設爲靜態,我如何能夠綁定它?請給我一個這個例子。 –

+0

@Night Walker:我現在不在我的電腦,但看到以下鏈接:http://stackoverflow.com/questions/936304/problem-binding-to-static-property –

+0

現在,我認爲更深的靜態不會幫助因爲我需要獲取組合框中的選定項目,而且我會遇到問題如果我也開始使用這些靜態組合。 –

1

你爲什麼要設置項目源的風格?

你可以試試這個代碼:

<my:DataGridTemplateColumn Header="Number of Copies" > 
        <my:DataGridTemplateColumn.CellTemplate> 
         <DataTemplate> 
          <ComboBox ItemsSource="{Binding Path=LifeAreaList}" > 
           <ComboBox.ItemTemplate> 
           <DataTemplate> 
            <Label Content="{Binding .}"></Label> 
           </DataTemplate> 
           </ComboBox.ItemTemplate> 
          </ComboBox> 
         </DataTemplate> 
        </my:DataGridTemplateColumn.CellTemplate> 
       </my:DataGridTemplateColumn> 

定義數據模板DataGridTemplateColumn如果LifeAreaList是複雜的類集合,並且希望在自定義的方式來顯示它。

+0

LifeAreaList is List

+0

我試過像,我仍然看到那裏是空的組合框。 DataGridTextColumn綁定的其他列正常工作。 –

+0

你可以用TemplateColumn試試嗎? – RockWorld

0

我會嘗試使用PresentationTraceSources.TraceLevel =「High」定期DataGridColumn,看看你是否有綁定問題。

1

你不應該在樣式中設置ItemsSource,該列自身has such a property可能會覆蓋任何可能嘗試在樣式中設置的內容。此外,您嘗試將其設置爲錯誤的樣式(該樣式適用於顯示模式),您可以嘗試將其設置爲EditingElementStyle,但我不建議這樣做。

相關問題