Issue with binding to GridLayout to Android

后端 未结 2 615
难免孤独
难免孤独 2020-12-21 10:41

I create game using technology Mono. While writing, I have a problem. I need create a grid (4 to 5) with pictures. I thought to apply here GridLayout or GridView. But I do

2条回答
  •  [愿得一人]
    2020-12-21 11:11

    There is a GridView available in Android - but I've personally never used the GridView with databinding in mvvmcross - but I've heard it's quite simple to add - see https://github.com/slodge/MvvmCross/issues/37

    As an alternative to the grid view, you could build your own Grid using some combination of vertical and horizontal LinearLayouts. You might do this by having an outer linearlayout like:

    
    

    with the row template containing

    
    

    and the cell containing just the ImageView


    Regardless of whether you use GridView or LinearLayouts, then you should be able to build a container ready for your individual ImageView squares.

    Once this is ready then changing the image shown in each square should be very straight-forward - it should just be a case of binding an ImageView's AssetImagePath to a property on the ViewModel object representing the square.

    ie. if your ViewModel is:

    public class MyViewModel : MvxViewModel
    {
        public List Rows {get;private set;}
    }
    

    where GameRow is:

    public class GameRow : MvxNotifyProperty
    {
        public List Cells {get;private set;}
    }
    

    where GameSquare is:

    public class GameSquare : MvxNotifyProperty
    {
        private string _icon;
        public string Icon 
        {
           get { return _icon; }
           set { _icon = value; RaisePropertyChanged(() => Icon);
        }
    }
    

    then the binding on each ImageView display should just be something like:

     {'AssetImagePath':{'Path':'Icon'}}
    

    Obviously you might not want to use icon paths directly in your ViewModel - you might prefer to use an enumeration instead. If you do this, then you might want to use a ValueConverter or a custom binding to display the correct image based on the current enumeration value.

    See the question and answer in how to bind an image src to resource drawable image with Mvvmcross? for some more information.

提交回复
热议问题