2010-03-04 42 views
2

我有一個ObservableCollection<string>列表,它綁定到組合框。該組合框位於「DataGridTemplateColumn」內的數據模板中。綁定組合框:排序字符串的源列表後文本消失

當顯示數據網格(包含所有行)時,顯示此組合框的列運行良好。用戶可以選擇組合框中的項目,並且當它被選中時,該字符串被綁定到單元格。 (僅供參考:datagrid綁定到另一個ObservableCollection,以便單元格文本在列表中更新 - 但我認爲它與我的問題無關)。

這一切都很好,但是當我去'添加'ObservableCollection<string>列表中的組合框綁定的另一個項目並執行排序時出現問題。該文本在一些先前修改的組合框的「文本框」部分中消失。如果我不排序列表,(只需添加一個新值),一切都很好。

我認爲發生的事情是,當我重新排序列表時,綁定被搞砸了。由於列表已經「更改」,列表中的字符串順序現在不同,因此綁定不知道要顯示的內容。

我如何得到這個工作?當我重新排列ObservableCollection<string>列表時,先前選擇的組合框的文本消失。

<DataGridTemplateColumn>含有組合框是:

<WpfToolkit:DataGridTemplateColumn 
       Header="Category" Width="1*" 
       CellTemplate="{StaticResource ComboBoxCellDataTemplate}" 
       CellEditingTemplate="{StaticResource ComboBoxCellEditingTemplate}"/> 

...和相關的DataTemplates是:

<DataTemplate x:Key="ComboBoxCellDataTemplate"> 
    <Label x:Name="lblCombo" Content="{Binding Category}" Style="{StaticResource BaseLabelCellStyle}" /> 
    <DataTemplate.Triggers> 
     <DataTrigger Binding="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.Categories, Mode=TwoWay}" Value="Both"> 
      <Setter TargetName="lblCombo" Property="IsEnabled" Value="False" /> 
     </DataTrigger> 
    </DataTemplate.Triggers> 
</DataTemplate> 

<DataTemplate x:Key="ComboBoxCellEditingTemplate"> 
    <!-- min=60, max=600 also, add in a 'specific' scalar value --> 
    <ComboBox 
     x:Name="comboBox" 
     ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.Categories, Mode=TwoWay}" 
     SelectedItem="{Binding Category}" LostFocus="comboBox_LostFocus" IsEditable="True" PreviewKeyDown="comboBox_PreviewKeyDown" MaxDropDownHeight="100" /> 

    <DataTemplate.Triggers> 
     <DataTrigger Binding="{Binding Enabled}" Value="False"> 
      <Setter TargetName="comboBox" Property="IsEnabled" Value="True" /> 
     </DataTrigger> 
     <DataTrigger Binding="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.Categories, Mode=TwoWay}" Value="Both"> 
      <Setter TargetName="comboBox" Property="IsEnabled" Value="True" /> 
     </DataTrigger> 
    </DataTemplate.Triggers> 
</DataTemplate> 

注意,大多數這個代碼是由塞繆爾·莫拉在http://sweux.com/blogs/smoura/index.php/tag/datagridcolumn/

回答

2

嘿,我想我有你的解決方案。就在下面的行添加到您的Datagrid定義

SelectionUnit="Cell" 

我不知道怎麼樣,它爲我工作:)只要給它一個嘗試,讓我知道,如果它幫助。