我有一个ObservableCollection<string>
列表,它绑定到一个组合框。此组合框位于“DataGridTemplateColumn”内的数据模板中。
当显示数据网格(包含所有行)时,显示此组合框的列就可以正常工作。用户可以选择组合框中的项目,当它被选中时,字符串被绑定到单元格。(仅供参考:数据网格绑定到另一个 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>
请注意,此代码的大部分由 Samuel Moura 在http://sweux.com/blogs/smoura/index.php/tag/datagridcolumn/