【问题标题】:Xamarin, MVVMCross show DisplayMemberPath insteadXamarin、MVVMCross 改为显示 DisplayMemberPath
【发布时间】:2017-06-16 09:21:52
【问题描述】:

我正在使用 Xamarin 和 MVVMCross 构建一个原生 android 项目。我使用 Mvx.MvxSpinner 作为元素来加载我的数据(这是 MVVMCross 方式)。

我有以下问题:我有一个包含不同数据元素的类和一个微调器,我将 new List<DataClass>() 与其中的元素绑定在一起。 有没有办法实际绑定到数据类中的 Name 属性(与 WPF 中的 DisplayMemberPath 相同)

数据类:

public class DataClass
{
   public string Name { get; set; }
}

视图模型:

public ObservableCollection<DataClass> Lines
{
    get => GetPropertyValue<ObservableCollection<DataClass>>();
    set => SetPropertyValue(value);
}

查看:

<Mvx.MvxSpinner
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    local:MvxBind="ItemsSource Lines; SelectedItem SelectedLine" />

【问题讨论】:

  • 如果不可能,我也可以只使用适配器。
  • 如果在 XML 绑定中将 SelectedLine 更改为 SelectedLine.Name 会发生什么?

标签: xamarin xamarin.android mvvmcross


【解决方案1】:

默认方法

默认情况下,MvvmCross 只会调用您列出的模型的ToString。因此,您可以直接覆盖 ToString 以返回名称。

public class DataClass
{
    public string Name { get; set; }

    public override string ToString() => Name;
}

模板方法

如果您想更好地控制外观和绑定,您可以创建自定义 Xml 模板。

<Mvx.MvxSpinner
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    local:MvxBind="ItemsSource Lines; SelectedItem SelectedLine"
    local:MvxDropDownItemTemplate="@layout/item_template_dropdown"
    local:MvxItemTemplate="@layout/item_template_spinner" />

MvxItemTemplate 是控件处于静止状态(默认)时使用的模板。而MvxDropDownItemTemplate是spinner处于选择状态时使用的模板。

项目模板示例

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:local="http://schemas.android.com/apk/res/Project.Ui.Droid"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        local:MvxBind="Text Name" />
</FrameLayout>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-23
    • 2020-09-25
    • 2013-07-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多