【发布时间】:2017-07-16 22:52:23
【问题描述】:
我的 ViewModel 中有一个 Xamarin.Forms.Color 对象的二维数组。我想将此数组绑定到我的视图中的一堆 BoxView 对象,并根据数组的内容设置它们的颜色。我知道如何绑定到 ViewModel 上的字符串、int 或 bool 等属性,但如果我要绑定的特定值是系统提供的对象,比如 Color,我不知道。
代码sn-ps:
ViewModel 有我想绑定到的这个属性:
public GameGrid<Color> Board;
View 不是在 XAML 中声明的,而是通过 C# 代码声明的。我要绑定的属性是 BoxView 的 ColorProperty,如下所示:
boxView.BindingContext = _viewModel.Board[row, col];
boxView.SetBinding(BoxView.ColorProperty, ".", BindingMode.Default);
鉴于 _viewModel.Board 属性是二维数组或颜色类型中的一个单元格,我如何绑定到它?这 ”。”是一个占位符 - 我不知道我应该在那里放置什么。
GameGrid 类包装了一个二维数组,因为我认为我需要实现 INotifyPropertyChanged,以便稍后我可以对该数组中的单个元素更改做出反应,以便为游戏移动设置动画。为了完整起见,它的代码在这里:
public class GameGrid<T> : INotifyPropertyChanged
{
private T[,] _array;
public GameGrid(int rows, int columns)
{
_array = new T[rows, columns];
}
public T this[int a, int b]
{
get
{
return _array[a, b];
}
set
{
_array[a, b] = value;
RaisePropertyChanged(nameof(GameGrid<T>));
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(
this, new PropertyChangedEventArgs(propertyName));
}
}
如果我将我的二维数组更改为一个简单的对象,例如;
public class Wrapper
{
public Color BindThis { get; set; }
}
public GameGrid<Wrapper> Board;
像这样绑定到该属性非常简单:
boxView.SetBinding(BoxView.ColorProperty, "BindThis", BindingMode.Default);
但这似乎是不必要的复杂。
【问题讨论】:
标签: c# mvvm xamarin.forms