2016-06-28 62 views
1

到目前为止,我有一个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有可能吗?

+0

不,我知道的。可能的选项是使用Converter或视图模型中的一个属性,它返回最后一个元素。 –

回答

3

解决方案1:

您可以使用自定义转换器来实现这一点:

Converter类:

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, ... " /> 
+0

在属性的情况下,如果发生'CollectionChanged'事件,则想要触发所述属性的更改通知。 –

相关问题