You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

设置ElementStyle后DataGridComboBoxColumn下拉框选中同步问题求助

问题原因及解决方案

你遇到的这个问题,核心原因是共享的CollectionViewSource实例导致所有ComboBox同步选中状态:

你在DataGrid.Resources里定义的<CollectionViewSource x:Key="ItemTypes" .../>是单例资源(默认x:Shared=True),当给DataGridComboBoxColumn设置自定义ElementStyle后,每一行非编辑状态下的ComboBox都会绑定到同一个CollectionView实例。而CollectionView本身维护了一个CurrentItem属性,所有绑定到同一个CollectionView的控件会自动同步这个CurrentItem,所以你选一个下拉框,其他的都会跟着变。

不设置ElementStyle时,WPF默认的DataGridComboBoxColumn元素样式内部会为每一行的ComboBox创建独立的视图上下文,避免了共享CollectionView的问题,所以每个下拉框能独立选中。


解决方法(任选其一即可)

方法1:让CollectionViewSource不共享

给CollectionViewSource加上x:Shared="False"属性,这样每个控件获取这个资源时都会创建新的实例,避免共享CurrentItem:

<DataGrid.Resources>
    <CollectionViewSource x:Key="ItemTypes" x:Shared="False" Source="{Binding AllowedItems}" />
</DataGrid.Resources>

方法2:直接绑定AllowedItems,不使用CollectionViewSource

既然你的AllowedItems已经是枚举集合,不需要额外的视图处理,可以直接跳过CollectionViewSource,直接绑定到视图模型的AllowedItems:

<DataGridComboBoxColumn Header="Item Type"
                        ItemsSource="{Binding DataContext.AllowedItems, RelativeSource={RelativeSource AncestorType=DataGrid}}"
                        SelectedItemBinding="{Binding ItemType, UpdateSourceTrigger=PropertyChanged}">
    <DataGridComboBoxColumn.ElementStyle>
        <Style TargetType="{x:Type ComboBox}" BasedOn="{StaticResource {x:Type ComboBox}}">
        </Style>
    </DataGridComboBoxColumn.ElementStyle>
</DataGridComboBoxColumn>

方法3:在ElementStyle中显式绑定SelectedItem

如果一定要用CollectionViewSource,可以在自定义的ElementStyle里给ComboBox显式绑定SelectedItem,确保每个行的绑定独立:

<DataGridComboBoxColumn.ElementStyle>
    <Style TargetType="{x:Type ComboBox}" BasedOn="{StaticResource {x:Type ComboBox}}">
        <Setter Property="SelectedItem" Value="{Binding ItemType, UpdateSourceTrigger=PropertyChanged}" />
    </Style>
</DataGridComboBoxColumn.ElementStyle>

内容的提问来源于stack exchange,提问作者AKJ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 03:09:56