如何用XAML Behaviors绑定DataGrid ComboBoxColumn的SelectionChanged事件
解决DataGridComboBoxColumn中SelectionChanged事件命令绑定失效问题
问题核心原因
DataGrid的列(如DataGridComboBoxColumn)是脱离可视化树的元素,它们不直接包含在DataGrid的可视化结构中,因此常规的RelativeSource或ElementName绑定方式无法找到目标DataGrid的DataContext,导致运行时DataContext为null,绑定失效。而IntelliSense能识别命令只是XAML编辑器的静态语法分析,不代表运行时上下文有效。
可行解决方案
方案1:使用{x:Reference}直接引用DataGrid
x:Reference不依赖可视化树,通过元素名称直接引用目标控件,适合这种场景:
<behaviors:InvokeCommandAction EventName="SelectionChanged" Command="{Binding DataContext.TestCommand, Source={x:Reference MyGrid}}"/>
方案2:借助已有的CollectionViewSource绑定
因为CurrenciesList这个CollectionViewSource的DataContext和DataGrid的父级DataContext一致,可通过它间接绑定:
<behaviors:InvokeCommandAction EventName="SelectionChanged" Command="{Binding DataContext.TestCommand, Source={StaticResource CurrenciesList}}"/>
方案3:替换为DataGridTemplateColumn
将DataGridComboBoxColumn换成DataGridTemplateColumn,内部放置ComboBox,此时ComboBox属于可视化树,就能使用常规的RelativeSource或ElementName绑定:
<DataGridTemplateColumn Header="Currency"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <ComboBox ItemsSource="{Binding Source={StaticResource CurrenciesList}}" DisplayMemberPath="Name" SelectedValuePath="Code" SelectedValue="{Binding CurrencyCode}"> <behaviors:Interaction.Triggers> <behaviors:EventTrigger EventName="SelectionChanged"> <behaviors:InvokeCommandAction Command="{Binding DataContext.TestCommand, RelativeSource={RelativeSource AncestorType=DataGrid}}"/> </behaviors:EventTrigger> </behaviors:Interaction.Triggers> </ComboBox> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn>
补充说明
你之前在DataGrid的Button上能用RelativeSource或ElementName绑定成功,是因为Button属于DataGridCell的可视化树结构,能正常找到DataGrid的上下文;而列本身不在可视化树中,所以这两种方式无法生效。
内容的提问来源于stack exchange,提问作者George
相关产品推荐
相关产品推荐

