2010-03-04 37 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" 

我不知道怎么样,它为我工作:)只要给它一个尝试,让我知道,如果它帮助。