【问题标题】:Xamarin Forms ListVew Binding - Bind ViewCell Label to a MethodXamarin 表单 ListVew 绑定 - 将 ViewCell 标签绑定到方法
【发布时间】:2018-11-15 01:10:30
【问题描述】:

我正在通过 MVVM 方法使用 Xamarin Forms,它运行良好。

我需要向现有 ListView 添加功能,以便在绑定值为某个值时显示文本。

这里是生成描述的单元格

   <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <StackLayout>
                    <Label Text="{Binding Description}"  x:Name="lblDescription" 
               Style="{DynamicResource ListItemTextStyle}" />
                </StackLayout>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>

有没有什么方法基本上只显示标签是以下功能是真的(这可能在视图模型或代码后面)例如:

private bool IsDescriptionOk(string description)
    {
       //Look up description possibly in another lookup list
    }

id 想将可见的绑定到方法上,比如:

Visible="{Binding IsDescriptionOk}"

但由于它在列表视图中,如果有意义,id 是否需要传入项目索引?

【问题讨论】:

  • 为什么需要传递索引?为什么不能只根据 Description 属性的长度返回一个布尔值?
  • 这只是一个例子,我想查找实际描述,例如:如果描述是“在线”,则返回 false,如果描述是“处理中”,则返回 true 等。 ...

标签: listview xamarin.forms binding


【解决方案1】:
private string _description = null;

public string Description {
  get {
    if (_description == null) {
      // method to fetch/build description 
      _description = GetDescription();
    }
    return _description;
  }

public bool IsDescriptionOK {
  get {
    if ((Description == "Online") || (other values here...)) return false;
    return true;
  }
}

【讨论】:

  • 谢谢,但我仍然不确定如何从 xaml 绑定运行 ypur 示例中的 IsdescriptionOk 函数
  • 来自 YOUR 示例代码:Visible="{Binding IsDescriptionOk}"
【解决方案2】:

我想可能有多种方法可以解决此类问题。其中之一可能是使用IValueConverter。像这样的:

<ViewCell>
    <StackLayout>
        <Label
            Text="{Binding Description}"
            Style="{DynamicResource ListItemTextStyle}"
            IsVisible="{Binding Description, Converter="{StaticResource ItemStatusToVisiblityConverter}" />
    </StackLayout>
</ViewCell>

但是,我认为List 应该只包含可见项,否则您可能会有多个空的ListItems。

【讨论】:

  • 感谢您的回复 - 有什么方法可以调用函数吗?因为我所做的只是比较另一个对象中的条目列表
  • 您可以将此“函数”移动到 IValueConverter 并将“另一个对象”作为参数传递给 IValueConverter。
  • 但是,为什么不在将列表分配给列表之前先过滤列表呢?听起来这对你来说更有意义。
  • 感谢您到目前为止的帮助,您是否有示例说明 IValueConverter 在该场景中的外观?以一个简单的形式,所以我可以建立在它之上。上面的例子对我来说有点复杂。
猜你喜欢
  • 2021-04-05
  • 2019-01-29
  • 2020-02-10
  • 2021-08-17
  • 2021-11-26
  • 2016-12-20
  • 2019-12-01
  • 2019-03-19
  • 1970-01-01
相关资源
最近更新 更多