【问题标题】:Binding to last array element绑定到最后一个数组元素
【发布时间】:2016-06-28 12:52:18
【问题描述】:

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

【问题讨论】:

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

标签: c# arrays wpf xaml data-binding


【解决方案1】:

解决方案 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, ... " />

【讨论】:

  • 如果是CollectionChanged,则需要为该属性触发更改通知。
猜你喜欢
  • 2021-03-14
  • 2019-04-02
  • 2011-07-21
  • 1970-01-01
  • 1970-01-01
  • 2017-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多