c#-使用MvvmLight和Xamarin.iOS将属性绑定到ViewModel
作者:互联网
我已经使用MvvmLight很长时间了,非常适合我对Windows和Windows Phone开发的需求,但是我对版本5中引入的新Xamarin.iOS绑定功能感到困惑.
我已经检查了Flowers示例,并尝试创建一个无法按预期工作的非常简单的绑定:update操作仅执行一次…
这里是视图控制器的代码:
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; }
}
有人有一个可行的例子,还有一些解释吗?
解决方法:
您必须将在SetBinding中创建的Binding存储在ViewController中,否则,一旦离开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);
}
}
我相信这些更改可以解决您的问题.
标签:xamarin,mvvm-light,ios,c,mvvm 来源: https://codeday.me/bug/20191028/1954637.html