RelayCommand stops working after a while

前端 未结 2 1648
-上瘾入骨i
-上瘾入骨i 2020-12-07 01:19

I am facing some problems using GalaSoft\'s RelayCommand.

I have a NextCommand property that works, but only several times.

Afterwards, it s

相关标签:
2条回答
  • 2020-12-07 01:52

    Two words: Garbage Collector

    In your example project--which you should post the relevant bits of to make your question future-proof--you set the DataContext on your window like this:

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
    
            var logic  = new LogicObject();
            DataContext = logic.Collection;
        }
    }
    

    Because nothing else retains a reference to the LogicObject created here, it will be collected at the next opportunity.

    The command stops functioning because in LogicObject, you set the NextCommand of the ItemCollection to use private members of the soon-to-be-collected LogicObject:

    public class LogicObject
    {
        public LogicObject()
        {
            Collection = new ItemCollection();
            Collection.NextCommand = new RelayCommand(AddItem, CanAddItem);
            AddItem();
        }
    
        private bool CanAddItem()
        {
            // snip...
        }
    
        private void AddItem()
        {
            // snip...
        }
    }
    

    Once LogicObject is collected, the command can no longer work because it no longer has references to valid methods (AddItem and CanAddItem). This is why the isAlive field on both of the RelayCommand's weak references to the methods is false.

    You can fix this by just hanging on to the LogicObject, or by moving the AddItem and CanAddItem methods into the collection.


    To get in the spirit of GIFs for this question, here's one that shows the button stop working as soon as a Gen 0 collection occurs.

    Desktop capture showing button failing when GC occurs

    0 讨论(0)
  • 2020-12-07 01:53

    why dont you simply use the methods from ICollectionView? there you have:

    • MoveCurrentTo
    • MoveCurrentToFirst
    • MoveCurrentToLast
    • MoveCurrentToNext
    • MoveCurrentToPrevious
    • and other nice stuff

    something like this

     private ICollectionView MyView {get;set;}
    
    
     this.MyView = CollectionViewSource.GetDefaultView(this._items);
    
    
     if (!this.MyView.IsCurrentBeforeFirst)
     {
         this.MyView.MoveCurrentToPrevious();
     }
    
    0 讨论(0)
提交回复
热议问题