XPath : Bind to last item of collection

后端 未结 2 1597
野的像风
野的像风 2021-01-24 12:16

Can I Bind TextBox.Text to last item of an ObservableCollection ?

I tried this:



        
2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-24 12:47

    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:

    Bind using a value converter

    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.

    Bind to the current item in the collection view

    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.

提交回复
热议问题