【问题标题】:Xamarin and MVVM - How can I bind a Boxview in my View to an array of Color in my ViewModel?Xamarin 和 MVVM - 如何将 View 中的 Boxview 绑定到 ViewModel 中的 Color 数组?
【发布时间】: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


    【解决方案1】:

    看来您的方向是正确的。单个点 (.) 是绑定到 BindingContext 本身的语法;不是BindingContext 上的属性,而是当前BindingContext 的对象。

    您是否尝试过仅使用 . 作为 Binding 表达式运行代码?

    BoxView.ColorXamarin.Forms.Color 类型,所以你应该可以直接绑定到它。

    【讨论】:

    • 知道这一点很有用——这就是绑定到 BindingContext 本身的语法!我刚试了一下。我将 BoxView 初始化为灰色,这很好用,因为视图开始将 BoxView 显示为灰色。稍后,为了响应单击事件,我将 ViewModel 中的颜色更改为不同的颜色 - 并且该更新似乎不起作用 - BoxView 保持灰色。所以这一切都有效!
    • 您的 INPC 无法正常工作,因为您说属性 GameGrid&lt;T&gt; 已更新,但没有该名称的属性。更好的解决方案是在GameGrid&lt;T&gt; 上设置一个通用事件,以在更新时发出信号。然后,VM 可以订阅该事件并使用 nameof(Board) 向自身发送信号 PropertyChanged
    • 这是有道理的。我要试试看!如果解决了,我会回来将此标记为答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-29
    • 1970-01-01
    • 2013-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-31
    相关资源
    最近更新 更多