使用 MVVM 将新元素添加到 WPF 中 DataGrid 中的 ComboBox

Adding new element to a ComboBox which is in a DataGrid in WPF using MVVM

我有一个 DataGrid,其中包含 Transactions。我有一个 InterestOrDividend 列,我可以在其中 select 使用 ComboBox 的值。这很好用。

一项新功能是输入一个值并将其添加到可能性列表中。我将 IsEditable 设置为 true 并从 http://schemas.microsoft.com/expression/2010/interactivity

添加了 Interaction.Triggers

问题一: 似乎 InterestOrDividendSelectionChangedCommand 不仅在 selection 更改时触发,而且在我滚动 DataGrid 时也会触发,这样的行进入视图,在 InterestOrDividend 列中具有非空值。此外,当输入新值(不在列表中)时,事件不会触发。

问题二: 我想绑定ComboBoxText属性来获取新增的值。似乎事件在 Text 属性 更改之前触发,所以我得到了旧值。

<DataGridTemplateColumn Header="{x:Static r:Resource.InterestOrDividend}"
   CellTemplate="{StaticResource InterestOrDividendEditingTemplate}"
   CellEditingTemplate="{StaticResource InterestOrDividendEditingTemplate}" />

<DataTemplate x:Key="InterestOrDividendEditingTemplate">
        <ComboBox ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, 
                            AncestorType={x:Type DataGrid}}, Path=DataContext.AppData.AlienTypeObjects}" 
                  SelectedItem="{Binding InterestOrDividend}" 
                  DisplayMemberPath="FullName" 
                  IsEditable="True" 
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="SelectionChanged">
                    <i:InvokeCommandAction Command="{Binding RelativeSource={RelativeSource FindAncestor, 
                        AncestorType={x:Type DataGrid}}, 
                        Path=DataContext.InterestOrDividendSelectionChangedCommand}"
                        CommandParameter="{Binding RelativeSource={RelativeSource  FindAncestor, 
                        AncestorType={x:Type ComboBox}}, Path=Text}"
                                           />
                </i:EventTrigger>
            </i:Interaction.Triggers>
        </ComboBox>
</DataTemplate>

这是我的解决方案。我没有使用 EventTrigger,而是在 NewInterestOrDividend 的 setter 中捕获了新元素。重要的是 UpdateSourceTriggerLostFocus。当 InterestOrDividend 为空并且您更改焦点时,NewInterestOrDividend 中的 value 包含新值。

    <DataTemplate x:Key="InterestOrDividendEditingTemplate">
        <ComboBox ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, 
                            AncestorType={x:Type DataGrid}}, Path=DataContext.AppData.AlienTypeObjects}" 
                  DisplayMemberPath="FullName" Style="{StaticResource ComboBoxError}" 
                  IsEditable="True" 
                  SelectedItem="{Binding InterestOrDividend, UpdateSourceTrigger=LostFocus}" 
                  Text="{Binding NewInterestOrDividend, UpdateSourceTrigger=LostFocus}">
        </ComboBox>
    </DataTemplate>