Xamarin Forms:如何为网格内单击的按钮添加背景颜色(单词搜索游戏)

Posted

技术标签:

【中文标题】Xamarin Forms:如何为网格内单击的按钮添加背景颜色(单词搜索游戏)【英文标题】:Xamarin Forms: How to add background color for clicked button inside grid(Word Search Game) 【发布时间】:2021-01-15 19:07:44 【问题描述】:

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

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, 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 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 供参考。如何仅更改单击按钮的背景颜色?

【问题讨论】:

【参考方案1】:

您不需要设置 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);

在视图模型中

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;
  //...

【讨论】:

以上是关于Xamarin Forms:如何为网格内单击的按钮添加背景颜色(单词搜索游戏)的主要内容,如果未能解决你的问题,请参考以下文章

我们如何处理 Xamarin Forms Picker 的完成按钮单击事件?

如何为 Xamarin.Forms 中的段控件设置圆角

将按钮与没有 ListView 间隔的 Xamarin.Forms 网格底部对齐

如何为 Xamarin Forms 应用程序创建 Nuget 包

Xamarin Forms:如何为自定义字体设置 FontAttributes Bold

更改 Xamarin.Forms 按钮单击的颜色