【问题标题】:Pass index value to collection in XAML binding expression将索引值传递给 XAML 绑定表达式中的集合
【发布时间】:2019-03-09 20:52:25
【问题描述】:

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

我可以将标签和按钮的“文本”属性绑定到字符串,使用 INotifyPropertyChanged 并为我的按钮实现 Command 接口,很酷,这一切都很好而且花花公子。

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

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

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

public List<string> MessageCollection;

这在视图中(XAML 内容页面)

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

我在 Google 上搜索了一段时间,并在 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]}"/>

等等。

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

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

【问题讨论】:

  • 绑定一个重复元素,例如ItemsControl到列表中,并在ItemTemplate as shown herehere中添加&lt;Label Text="{Binding}"/&gt;
  • 谢谢,这些示例适用于 WPF,但将它们适应 Xamarin.Forms 并不难。 - 我仍在研究解决方案。
  • XAML ix XAML,不管下面的堆栈是什么。功能或绑定语法可能存在差异,但概念相同 - 项目控件、组合、数据绑定
  • 是的,你是对的!感谢您以如此清晰的方式陈述它。很有帮助。

标签: c# xamarin.forms


【解决方案1】:

这个语法应该可以工作

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

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

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

【讨论】:

  • 谢谢,我会去试试这个,然后把我的结果贴出来以供将来参考。
【解决方案2】:

您可以尝试以下格式。

示例代码

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

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

【讨论】:

  • 谢谢,我会尝试并发布我的结果。
【解决方案3】:

尝试使用转换器如下...

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-08
    • 1970-01-01
    • 2012-03-01
    • 2011-02-10
    • 2020-02-25
    • 1970-01-01
    相关资源
    最近更新 更多