XPath : Bind to last item of collection

风格不统一 提交于 2019-12-20 04:25:06

问题


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

I tried this:

<TextBox Text={Binding XPath="Model/CollectionOfString[last()]"/>

But it doesn't bind.

Thank you.


回答1:


Please try the method following,

1, use IValueConverter.

class DataSourceToLastItemConverter : IValueConverter
{
    public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        IEnumerable<object> items = value as IEnumerable<object>;
        if (items != null)
        {
            return items.LastOrDefault();
        }
        else return Binding.DoNothing;
    }

    public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new System.NotImplementedException();
    }
}

Then binding like this:

<Grid>
    <Grid.Resources>
        <local:DataSourceToLastItemConverter x:Key="DataSourceToLastItemConverter" />
    </Grid.Resources>
    <TextBox Text="{Binding Path=Model.CollectionOfString,Converter={StaticResource DataSourceToLastItemConverter}}"/>
</Grid>



回答2:


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.



来源:https://stackoverflow.com/questions/12778880/xpath-bind-to-last-item-of-collection

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!