簡體   English   中英

WPF DataGrid CellEditEnded 事件

[英]WPF DataGrid CellEditEnded event

每次用戶編輯我的 DataGrid 單元格的內容時,我都想知道。 有 CellEditEnding 事件,但在對 DataGrid 綁定到的集合進行任何更改之前調用它。

我的數據網格綁定到ObservableCollection<Item> ,其中Item是一個類,從 WCF mex 端點自動生成。

了解用戶每次對集合進行更改時的最佳方式是什么。

更新

我試過 CollectionChanged 事件,當Item被修改時它不會被觸發。

您可以在數據網格的屬性成員的綁定上使用UpdateSourceTrigger=PropertyChanged 這將確保當 CellEditEnding 被觸發時,更新已經反映在 observable 集合中。

見下文

<DataGrid SelectionMode="Single"
          AutoGenerateColumns="False"
          CanUserAddRows="False"
          ItemsSource="{Binding Path=Items}" // This is your ObservableCollection
          SelectedIndex="{Binding SelectedIndexStory}">
          <e:Interaction.Triggers>
              <e:EventTrigger EventName="CellEditEnding">
                 <cmd:EventToCommand PassEventArgsToCommand="True" Command="{Binding EditStoryCommand}"/> // Mvvm light relay command
               </e:EventTrigger>
          </e:Interaction.Triggers>
          <DataGrid.Columns>
                    <DataGridTextColumn Header="Description"
                        Binding="{Binding Name, UpdateSourceTrigger=PropertyChanged}" /> // Name is property on the object i.e Items.Name
          </DataGrid.Columns>

</DataGrid>

UpdateSourceTrigger = PropertyChanged 將在目標屬性更改時立即更改屬性源。

這將允許您捕獲對項目的編輯,因為將事件處理程序添加到 observable 集合更改事件不會觸發集合中對象的編輯。

如果您需要知道編輯的 DataGrid 項目是否屬於特定集合,您可以在 DataGrid 的 RowEditEnding 事件中執行以下操作:

    private void dg_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
    {
        // dg is the DataGrid in the view
        object o = dg.ItemContainerGenerator.ItemFromContainer(e.Row);

        // myColl is the observable collection
        if (myColl.Contains(o)) { /* item in the collection was updated! */  }
    }

我改用了“ CurrentCellChanged ”。

    <DataGrid
        Grid.Row="1"
        HorizontalAlignment="Center"
        AutoGenerateColumns="True"
        AutoGeneratingColumn="OnAutoGeneratingColumn"
        ColumnWidth="auto"
        IsReadOnly="{Binding IsReadOnly}"
        ItemsSource="{Binding ItemsSource, UpdateSourceTrigger=PropertyChanged}">
        <b:Interaction.Triggers>
            <!--  CellEditEnding  -->
            <b:EventTrigger EventName="CurrentCellChanged">
                <b:InvokeCommandAction Command="{Binding CellEditEndingCmd}" />
            </b:EventTrigger>
        </b:Interaction.Triggers>
    </DataGrid>

您應該在ObservableCollectionCollectionChanged事件上添加一個事件處理程序。

代碼片段:

_listObsComponents.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(ListCollectionChanged);

// ...


    void ListCollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {
        /// Work on e.Action here (can be Add, Move, Replace...)
    }

e.ActionReplace ,這意味着您的列表中的一個對象已被替換。 此事件當然是在應用更改后觸發的

玩得開心!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM