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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…