将索引值传递给 XAML 绑定表达式中的集合



我在Visual Studio 2017中编码并使用Xamarin.Forms。

我可以将标签和按钮的"文本"属性绑定到字符串中,使用 INotifyPropertyChanged 并为我的按钮实现命令界面,很酷,一切都很好,很花花公子。

我的 ViewModel 中有一个集合,它本质上是我的视图引用的一个类,它是一个 XAML 页面。

我现在要做的是将标签绑定到我的字符串集合的特定索引。

所以我在 VM(c# 类(中有这个

public List<string> MessageCollection;

这在视图(XAML 内容页(中

<Label Text="{Binding MessageCollection}"/>

我已经用谷歌搜索了一段时间,并在Stack-O上检查了其他问题,但还没有找到我问题的明确答案。

我想做的是这样的:

<Label Text="{Binding MessageCollection[0]}"/>

<Label Text="{Binding MessageCollection, Index="0"}"/>

继续

<Label Text="{Binding MessageCollection[0]}"/>
<Label Text="{Binding MessageCollection[1]}"/>
<Label Text="{Binding MessageCollection[2]}"/>

等等。

列表将在运行时修改,因为用户可以通过按钮和输入字段添加和删除字符串并编辑这些字符串的内容。

在绑定表达式中按索引引用集合的好方法是什么?

尝试使用转换器,如下所示...

public class ListToFirstObjectGetter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is System.Collections.IList list)
{
return list[0];
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}

此语法应该有效

<Label Text="{Binding MessageCollection[0]}"/>

但是,您只能绑定到公共属性,因此您需要使用 getter 声明MessageCollection

public List<string> MessageCollection { get; set; }

你可以试试以下格式。

示例代码

List<string> messageCollection;
string message = string.empty;
message = messageCollection.indexOf(your specific index no);

从上面的代码中,您可以从消息集合中检索特定的字符串。 现在,您可以将"消息"字符串绑定到视图。

最新更新