MvvmCross - 手动将视图添加到线性布局 - 在事件内访问模型

时间:2014-07-04 09:58:52

标签: android mvvmcross

我有一个ScrollView页面。我将在其中放入一些TextView和一些ListView。因为人们说:不能在ScrollView中使用ListView,所以我改用LinearLayout。

这是.axml:

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:local="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                local:MvxBind="Text Item.Info1"/>
    <LinearLayout
                android:orientation="vertical"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/linearLayout1" />
</ScrollView>

这是ViewModel:

public class ItemDetailViewModel : MvxViewModel{

    ...

    private Item _item;
    public Item Item {
        get { return this._item; }
        set {
            _item= value;
            RaisePropertyChanged(() => Item );
        }
    }

    ....

在View中,我手动将TextView添加到linearLayout1。我想在单击TextView时访问subItem。但我不知道该怎么做。您能否请看下面的评论和帮助?感谢。

protected override void OnCreate(Bundle bundle) {
    ItemDetailViewModel vm = this.ViewModel as ItemDetailViewModel ;
    RunOnUiThread(() =>
            {
                LinearLayout linearLayout1 = FindViewById<LinearLayout>(Resource.Id.linearLayout1);

                foreach (SubItem subItem vm.Item.SubItems)
                {
                    //I am stuck here, don't know how to access subItem in Click event??

                    TextView textView = new TextView(this);
                    textView.Text = subItem.itemName;
                    textView.Click += textView_Click;
                    linearLayout1.AddView(textView);

                    //I know there is another way to do this by using existed axml but ...
                    /*
                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        local:MvxBind="Text ItemName; Click DoSomethingWithItem" />
                    */
                    TextView textView = (TextView)LayoutInflater.Inflate(Resource.Layout.Sub_Item, null);
                    var set = this.CreateBindingSet<.., ItemDetailViewModel >();
                    set.Bind(textView ).To(vm => vm....); //How can I access subItem from vm??
                    set.Apply();

                }
            });
        });
....
private void adEquipmentTextView_Click(object sender, System.EventArgs e)
{
     //TODO:do something with subItem
}

1 个答案:

答案 0 :(得分:0)

你可以为每个方法创建一个匿名包装器吗?

即。而不是打电话:

                textView.Click += textView_Click;

呼叫:

                textView.Click += (s,e) => DoClickOn(subItem);