WPF-DataGrid中的ComboBox的SelectionChanged事件以及数据更新问题记录

代码:

			<DataGridTemplateColumn>
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <ComboBox SelectedItem="{Binding LTFamilySymbol,UpdateSourceTrigger=PropertyChanged}">
                            <i:Interaction.Triggers>
                                <i:EventTrigger EventName="SelectionChanged">
                                    <i:InvokeCommandAction Command="{Binding Path=DataContext.MyCommand,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=Window}}"></i:InvokeCommandAction>
                                </i:EventTrigger>
                            </i:Interaction.Triggers>
                        </ComboBox>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn> 

问题描述:combobox里面的选项改变以后,后台获取不到该值,甚至连DataGrid的SelectedItem都获取错误(不是报错),只有当你进入本行的其他cell以后,本行才能被激活,才不会出错。

解决办法:其实是有一个属性没有设定,就是Combobox的selecteditem属性绑定时,需要添加updatesourcetrigger=propertychanged。这样只要combobox的选项发生改变,立马就知道了。

注意:combobox的selectedchanged事件,在窗口启动的时候,会自动执行一次,如果此时datagrid绑定的源为空,则会出问题。而在已有源的情况下,不会发生该问题。找到问题,解决办法就简单了:在ViewModel中,对应的委托执行中,进行判断源是否为空即可。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用以下步骤将 ComboBoxSelectionChanged 事件绑定到 ViewModel 的一个命令: 1. 在 ViewModel 定义一个 ICommand 属性,用于处理 ComboBoxSelectionChanged 事件。 ```csharp private ICommand _comboBoxSelectionChangedCommand; public ICommand ComboBoxSelectionChangedCommand { get { if (_comboBoxSelectionChangedCommand == null) { _comboBoxSelectionChangedCommand = new RelayCommand<object>(ComboBoxSelectionChanged, CanComboBoxSelectionChanged); } return _comboBoxSelectionChangedCommand; } } private bool CanComboBoxSelectionChanged(object parameter) { // 可选:检查命令是否可用 return true; } private void ComboBoxSelectionChanged(object parameter) { // 处理 ComboBoxSelectionChanged 事件 } ``` 2. 在 XAML ,将 ComboBoxSelectionChanged 事件绑定到上面定义的命令,并使用 CommandParameter 属性将 ComboBox 本身作为参数传递给命令。 ```xml <ComboBox ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem}" SelectionChanged="{Binding ComboBoxSelectionChangedCommand}" CommandParameter="{Binding RelativeSource={RelativeSource Self}}"> <ComboBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding}" /> </DataTemplate> </ComboBox.ItemTemplate> </ComboBox> ``` 注意,在上面的代码,我使用了一个 RelayCommand 类来实现 ICommand 接口,你可以根据需要使用其他实现方式来绑定命令。另外,我还使用了 CommandParameter 属性将 ComboBox 本身作为参数传递给命令,这样在 ViewModel 就可以访问 ComboBox 的属性和方法了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值