Xamarin Forms:如何为网格内的单击按钮添加背景色Word搜索游戏 在ViewModel中

如何解决Xamarin Forms:如何为网格内的单击按钮添加背景色Word搜索游戏 在ViewModel中

我正在使用网格内的按钮来显示字母以实现单词搜索游戏。单击一个按钮时,整个按钮的背景颜色都会改变。我只需要更改所单击按钮的背景颜色即可。

Xaml.cs

void SetGridLayout(char[,] matrixToPrint)
{
    int numRows = matrixToPrint.GetLength(0);
    int numCols = matrixToPrint.GetLength(1);

    gridLayout.HorizontalOptions = Layoutoptions.FillAndExpand;
    gridLayout.SetBinding(Button.HeightRequestProperty,new Binding("Width",source: gridLayout));

    for (int row = 0; row < numRows; row++)
    {
        gridLayout.RowDeFinitions.Add(new RowDeFinition { Height = new GridLength(1,GridUnitType.Auto) });
    }
    for (int col = 0; col < numCols; coL++)
    {
        gridLayout.ColumnDeFinitions.Add(new ColumnDeFinition { Width = new GridLength(1,GridUnitType.Star) });
    }

    for (int rowIndex = 0; rowIndex < numRows; rowIndex++)
    {
        for (int columnIndex = 0; columnIndex < numCols; columnIndex++)
        {
            //button
            var Rowbutton = new Button
            {
                Text = Char.ToString(matrixToPrint[rowIndex,columnIndex]),VerticalOptions = Layoutoptions.FillAndExpand,HorizontalOptions = Layoutoptions.FillAndExpand,Padding = 0,Margin = 0,CommandParameter = rowIndex.ToString() + "," + columnIndex.ToString()
            };
            Rowbutton.SetBinding(View.BackgroundColorProperty,"ButtonBackgroundColor",BindingMode.TwoWay);
            Rowbutton.SetBinding(Button.CommandProperty,"ClickCommand");
            Rowbutton.SetBinding(Button.HeightRequestProperty,source: Rowbutton));

            // add the frame to the cuurent row / column in the newly created grid
            gridLayout.Children.Add(Rowbutton,columnIndex,rowIndex);
        }
    }
}

viewmodel中单击按钮的代码

private Color _buttonbackgroundColor = Color.White;
public Color ButtonBackgroundColor
{
    get { return _buttonbackgroundColor; }
    set
    {
        if (value == _buttonbackgroundColor)
            return;

        _buttonbackgroundColor = value;
        OnPropertyChanged("ButtonBackgroundColor");
    }
}

public Command ClickCommand => new Command((param) => OnSelectionChanged(param));
private void OnSelectionChanged(object param)
{
    string CurrentCordinate = param as string;
    Debug.WriteLine("CurrentCordinate:>>" + CurrentCordinate);
    
    if(!string.IsNullOrEmpty(CurrentCordinate))
    {
        if(CurrentSelection.Count == 0)
        {
            CurrentSelection.Add(CurrentCordinate);
            ButtonBackgroundColor = Color.Orange;
            LastCordinate = CurrentCordinate;
        }
        else
        {
            if(LastCordinate != CurrentCordinate)
            {
                string[] Lastbits = LastCordinate.Split(',');
                string[] Currentbits = CurrentCordinate.Split(',');

                int LastCordinateRow = ParsetoInt(Lastbits[0]);
                int LastCordinateCol = ParsetoInt(Lastbits[1]);

                int CurrentCordinateRow = ParsetoInt(Currentbits[0]);
                int CurrentCordinateCol = ParsetoInt(Currentbits[1]);

                if(IsSamePattern(LastCordinateRow,LastCordinateCol,CurrentCordinateRow,CurrentCordinateCol))
                {
                    CurrentSelection.Add(CurrentCordinate);
                    ButtonBackgroundColor = Color.Orange;
                    if(CheckIfWordSelected(CurrentSelection))
                    {
                        TotalAttempts++;
                        ButtonBackgroundColor = Color.Green;
                        CurrentSelection = new List<string>();
                        LastCordinate = string.Empty;
                        LastClickPattern = string.Empty;
                    }
                }
                else
                {
                    TotalAttempts++;
                    ButtonBackgroundColor = Color.White;
                    CurrentSelection = new List<string>();
                    LastCordinate = string.Empty;
                    LastClickPattern = string.Empty;
                }
                LastCordinate = CurrentCordinate;
            }
            else
            {
                TotalAttempts++;
                ButtonBackgroundColor = Color.White;
                CurrentSelection = new List<string>();
                LastCordinate = string.Empty;
                LastClickPattern = string.Empty;
            }
        }
    }
}

我已经上传一个示例项目here供参考。如何仅更改单击按钮的背景颜色?

解决方法

您无需设置 BackgroundColor 的绑定,因为该绑定将适用于您的情况下的所有按钮。解决方法是,可以将单击的按钮作为参数传递给命令,然后根据需要设置 BackgroundColor (似乎您也想传递字符串,因此可以定义一个类)

public class PassObject 
{
    public Button currentButton { get; set; }  // pass button

    public string Info { get; set; }  //pass the string 


    public PassObject(Button button,string str)
    {
        currentButton = button;
        Info = str;
    }
}
//button
var Rowbutton = new Button
{
    //...                    
    BackgroundColor = Color.Gray,// set CommandParameter out the statement
    // CommandParameter = rowIndex.ToString() + "," + columnIndex.ToString() 
};

//don't need to set bgcolor any more
//   Rowbutton.SetBinding(View.BackgroundColorProperty,"ButtonBackgroundColor",BindingMode.TwoWay);
                    
Rowbutton.SetBinding(Button.CommandProperty,"ClickCommand");

Rowbutton.SetValue(Button.CommandParameterProperty,new PassObject(Rowbutton,rowIndex.ToString() + "," + columnIndex.ToString()));

Rowbutton.SetBinding(Button.HeightRequestProperty,new Binding("Width",source: Rowbutton));

 // add the frame to the cuurent row / column in the newly created grid
gridLayout.Children.Add(Rowbutton,columnIndex,rowIndex);

在ViewModel中

private void OnSelectionChanged(object param)
{

  var obj = param as PassObject;

  var button = obj.currentButton;

  if(button.BackgroundColor==Color.Orange)
  {
        button.BackgroundColor = Color.Gray;
  }
  else
  {
     button.BackgroundColor = Color.Orange;
  }

  string CurrentCordinate = obj.Info;
  //...

enter image description here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?