WinUI3中WPF EventSetter的等效替代方案及DataGridComboBoxColumn事件处理
在WinUI3 Community Toolkit DataGrid中捕获DataGridComboBoxColumn的SelectionChanged事件
WinUI3中没有WPF里的EventSetter,可以通过以下几种方式实现类似需求:
方案1:使用XAML行为(Behaviors)绑定事件
先安装Microsoft.Xaml.Behaviors.WinUI NuGet包,再通过EventTrigger绑定SelectionChanged事件:
xmlns:interactivity="using:Microsoft.Xaml.Interactivity" xmlns:core="using:Microsoft.Xaml.Interactions.Core" <controls:DataGridComboBoxColumn x:Name="Whatever" DisplayMemberPath="Name" SelectedValuePath="Id" SelectedValueBinding="{Binding SelectedItemId}"> <controls:DataGridComboBoxColumn.EditingElementStyle> <Style TargetType="ComboBox"> <Setter Property="interactivity:Interaction.Behaviors"> <interactivity:BehaviorCollection> <core:EventTriggerBehavior EventName="SelectionChanged"> <core:InvokeCommandAction Command="{x:Bind ViewModel.ComboBoxSelectionChangedCommand}" CommandParameter="{Binding}" /> </core:EventTriggerBehavior> </interactivity:BehaviorCollection> </Setter> </Style> </controls:DataGridComboBoxColumn.EditingElementStyle> </controls:DataGridComboBoxColumn>
对应的ViewModel命令实现(MVVM模式):
public ICommand ComboBoxSelectionChangedCommand { get; } // 构造函数初始化 public YourViewModel() { ComboBoxSelectionChangedCommand = new RelayCommand<ComboBoxSelectionChangedEventArgs>(OnComboBoxSelectionChanged); } private void OnComboBoxSelectionChanged(ComboBoxSelectionChangedEventArgs args) { var selectedItem = args.AddedItems.FirstOrDefault(); // 编写选中变更后的处理逻辑 }
方案2:通过DataGrid的CellEditEnded事件判断处理
若无需在选中瞬间触发,可在编辑结束时通过DataGrid的CellEditEnded事件处理:
<controls:DataGrid x:Name="MyDataGrid" CellEditEnded="MyDataGrid_CellEditEnded"> <controls:DataGridComboBoxColumn x:Name="Whatever" ... /> </controls:DataGrid>
后台代码:
private void MyDataGrid_CellEditEnded(object sender, DataGridCellEditEndedEventArgs e) { if (e.Column == Whatever && e.EditingElement is ComboBox comboBox) { var selectedItem = comboBox.SelectedItem; // 编写选中变更后的处理逻辑 } }
方案3:自定义DataGridComboBoxColumn手动绑定事件
继承DataGridComboBoxColumn,重写生成编辑元素的方法,手动添加事件处理:
public class CustomDataGridComboBoxColumn : DataGridComboBoxColumn { protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem) { var comboBox = (ComboBox)base.GenerateEditingElement(cell, dataItem); comboBox.SelectionChanged += ComboBox_SelectionChanged; return comboBox; } private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { var comboBox = (ComboBox)sender; var selectedItem = comboBox.SelectedItem; // 编写选中变更后的处理逻辑 // 如需传递到页面,可定义自定义事件 SelectionChanged?.Invoke(this, e); } // 自定义事件供页面绑定 public event SelectionChangedEventHandler SelectionChanged; }
XAML中使用自定义列:
<local:CustomDataGridComboBoxColumn x:Name="Whatever" SelectionChanged="CustomDataGridComboBoxColumn_SelectionChanged" ... />
后台页面事件处理:
private void CustomDataGridComboBoxColumn_SelectionChanged(object sender, SelectionChangedEventArgs e) { // 编写选中变更后的处理逻辑 }
内容的提问来源于stack exchange,提问作者hellosantokki
相关产品推荐
相关产品推荐

