How to raise an event when DataGrid.ItemsSource is changed

前端 未结 3 1313
陌清茗
陌清茗 2020-12-05 02:39

I am new in WPF, and I am working with DataGrids and I need to know when the property ItemsSource is changed.

For example, I would need that when this instruction is

相关标签:
3条回答
  • 2020-12-05 02:54

    If you wnat to detect new row added can try DataGrid's InitializingNewItem or AddingNewItem Event.

    InitializingNewItem usage :

    Datagrid auto add item with data of parent

    0 讨论(0)
  • 2020-12-05 03:01

    Is this any help?

    public class MyDataGrid : DataGrid
    {
        protected override void OnItemsSourceChanged(
                                        IEnumerable oldValue, IEnumerable newValue)
        {
            base.OnItemsSourceChanged(oldValue, newValue);
    
            // do something here?
        }
    
        protected override void OnItemsChanged(NotifyCollectionChangedEventArgs e)
        {
            base.OnItemsChanged(e);
    
            switch (e.Action)
            {
                case NotifyCollectionChangedAction.Add:
                    break;
                case NotifyCollectionChangedAction.Remove:
                    break;
                case NotifyCollectionChangedAction.Replace:
                    break;
                case NotifyCollectionChangedAction.Move:
                    break;
                case NotifyCollectionChangedAction.Reset:
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-05 03:09

    ItemsSource is a dependency property, so it's easy enough to be notified when the property is changed to something else. You would want to use this in addition to code that you have, not instead of:

    In Window.Loaded (or similar) you can subscribe like so:

    var dpd = DependencyPropertyDescriptor.FromProperty(ItemsControl.ItemsSourceProperty, typeof(DataGrid));
    if (dpd != null)
    {
        dpd.AddValueChanged(myGrid, ThisIsCalledWhenPropertyIsChanged);
    }
    

    And have a change handler:

    private void ThisIsCalledWhenPropertyIsChanged(object sender, EventArgs e)
    {
    }
    

    Whenever the ItemsSource Property is set, the ThisIsCalledWhenPropertyIsChanged method is called.

    You can use this for any dependency property you want to be notified about changes.

    0 讨论(0)
提交回复
热议问题