繁体   English   中英

绑定到最后一个数组元素

[英]Binding to last array element

到目前为止,我有一个ObservableCollection<T>用于对象。 我总是希望将最后插入的元素显示到TextBlock 我在XAML中实现了两个解决方案,但都没有工作:

<TextBlock Text="{Binding Path=entries.Last().message, FallbackValue=...}" />

<TextBlock Text="{Binding Path=entries[entries.Length-1].message, FallbackValue=...}" />

这个工作,但引用第一个条目:

<TextBlock Text="{Binding Path=entries[0].message, FallbackValue=...}" />

我错过了什么吗? 是否可以使用纯XAML?

解决方案1:

您可以使用自定义转换器来实现此目的:

转换器类:

class LastItemConverter : 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();
    }
}

Xaml:

 <Application.Resources>
        <local:LastItemConverter  x:Key="LastItemConverter" />
 </Application.Resources>

 <TextBlock Text="{Binding Path=entries, Converter={StaticResource LastItemConverter}}" />

解决方案2:

另一种方法是在模型中创建一个返回条目的新属性:

public Object LastEntry => entries.LastOrDefault();

Xaml:

<TextBlock Text="{Binding Path=LastEntry, ... " />

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM