使用MvvmLight和Xamarin.iOS将属性绑定到ViewModel

3

我已经长期使用MvvmLight,它完美地适合我的Windows和Windows Phone开发需求,但是我在处理新的Xamarin.iOS绑定功能时遇到了问题,这些功能是在版本5中引入的。

我查看了Flowers示例,并尝试创建一个非常简单的绑定,但并没有像预期的那样工作:更新操作仅执行一次...

这里是视图控制器的代码:

 public partial class MainViewController : UIViewController
{
    private MainViewModel ViewModel { get; set; }

    public MainViewController()
        : base("MainViewController", null)
    {
        this.ViewModel = new MainViewModel();
    }

    public override void ViewDidLoad()
    {
        base.ViewDidLoad();

        this.SetBinding(() => this.ViewModel.IsUpdated).WhenSourceChanges(() =>
            {
                this.updateLabel.Text = this.ViewModel.IsUpdated ? "It's okay !" : "Nope ...";
            });

        this.updateButton.SetCommand("TouchUpInside", this.ViewModel.UpdateCommand);

    }
}

生成的部分类声明包含两个接口元素:
[Register ("MainViewController")]
partial class MainViewController
{
    [Outlet]
    MonoTouch.UIKit.UIButton updateButton { get; set; }

    [Outlet]
    MonoTouch.UIKit.UILabel updateLabel { get; set; }

    void ReleaseDesignerOutlets ()
    {
        if (updateLabel != null) {
            updateLabel.Dispose ();
            updateLabel = null;
        }

        if (updateButton != null) {
            updateButton.Dispose ();
            updateButton = null;
        }
    }
}

相关的ViewModel如下:

public class MainViewModel : ViewModelBase
{
    public MainViewModel()
    {
        this.UpdateCommand = new RelayCommand(() =>
            {
                this.IsUpdated = !this.IsUpdated;
            });
    }

    private bool isUpdated;

    public bool IsUpdated
    {
        get { return this.isUpdated; }
        set
        {
            this.Set<bool>(ref this.isUpdated, value);
        }
    }

    public RelayCommand UpdateCommand { get; private set; }
}

有人有一个可行的例子和一些解释吗?
1个回答

4

您需要在ViewController中存储SetBinding创建的绑定,否则它将在ViewDidLoad的范围内离开并消失。在Flowers示例中,该代码仅在视图加载期间运行。由于值的更改而不会运行。

public partial class MainViewController : UIViewController
{
    private Binding<bool, bool> _isUpdatedBinding;
    private MainViewModel ViewModel { get; set; }

    public MainViewController()
        : base("MainViewController", null)
    {
        this.ViewModel = new MainViewModel();
    }

    public override void ViewDidLoad()
    {
        base.ViewDidLoad();

        _isUpdatedBinding = this.SetBinding(() => this.ViewModel.IsUpdated).WhenSourceChanges(() =>
            {
                this.updateLabel.Text = this.ViewModel.IsUpdated ? "It's okay !" : "Nope ...";
            });

        this.updateButton.SetCommand("TouchUpInside", this.ViewModel.UpdateCommand);

    }
}

我相信这些更改应该可以解决您的问题。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接