Can I Bind
TextBox.Text
to last item of an ObservableCollection
?
I tried this:
It doesn't bind because you cannot use the XPath property on a-non XML data source; you have to use Path instead, and that property doesn't offer similar syntax. So you cannot directly bind to the last element of the collection unless you know the index of the last value. However there are a couple workarounds available:
It's not difficult to write custom value converter that takes the collection and "converts" it to its last element. Howard's answer gives a barebones converter that does this.
This is even easier to do, but it involves code-behind.
You can bind using Path=Model.CollectionOfString/
(note the slash at the end) if you have set the "current" item in the default collection view to be the last item in the collection. Do this inside your model:
// get a reference to the default collection view for this.CollectionOfString
var collectionView = CollectionViewSource.GetDefault(this.CollectionOfString);
// set the "current" item to the last, enabling direct binding to it with a /
collectionView.MoveCurrentToLast();
Be aware that if items are added to or removed from the collection, the current item pointer will not necessarily be adjusted automatically.