2013-10-04 110 views
1

我有以下GridView控件工作正常:WPF GridView的列綁定問題

<DataGrid IsReadOnly="true" 
      ItemsSource="{Binding CiList}" 
      AutoGenerateColumns="True" 
      SelectedItem="{Binding Path=CI}" /> 

如果我設置AutoGenerateColumns="False"和手動添加DataGridTextColumn,像這樣:

<DataGrid IsReadOnly="true" 
      ItemsSource="{Binding CiList}" 
      AutoGenerateColumns="False" 
      AlternatingRowBackground="Gainsboro" 
      AlternationCount="2" 
      Height="150" 
      SelectedItem="{Binding Path=CI}"> 
    <DataGridTextColumn Header="Name" 
         Binding="{Binding Path=Name}" /> 
</DataGrid> 

我得到一個InvalidOperationException「在使用ItemsSource之前,項目集合必須是空的。「

我在做什麼不正確?謝謝!

編輯:我使用MVVM模式,並且窗口的DataContext是我的ViewModel,其中CiList是屬性。

回答

2

你需要列標籤在DataGrid.Columns添加到網格

<DataGrid..> 
    <DataGrid.Columns> 
     <DataGridTextColumn Header="Name" Binding="{Binding Path=Name}" /> 
    </DataGridColumns> 
... 
+1

男孩我感到愚蠢。謝謝! RTFM,我猜... – Yevgeniy

+0

我多次犯了這個錯誤! –

2

需要內DataGrid.Columns

<DataGrid IsReadOnly="true" ItemsSource="{Binding CiList}" AutoGenerateColumns="False" AlternatingRowBackground="Gainsboro" AlternationCount="2" Height="150" SelectedItem="{Binding Path=CI}"> 
     <DataGrid.Columns> 
        <DataGridTextColumn Header="Name" Binding="{Binding Path=Name}" /> 
     </DataGrid.Columns> 
</DataGrid> 
1

認沽柱像下面定義的列:

<DataGrid IsReadOnly="true" ItemsSource="{Binding CiList}" AutoGenerateColumns="False" AlternatingRowBackground="Gainsboro" AlternationCount="2" Height="150" SelectedItem="{Binding Path=CI}"> 
    <DataGrid.Columns> 
     <DataGridTextColumn Header="Name" Binding="{Binding Path=Name}" /> 
    </DataGrid.Columns> 
</DataGrid>