在 N+1 视频 #34(进度)中,有一个 Android 版本使用 CreateBindingSet() 的示例,并不典型。但叙述者也简单地提到,在Windows平台上也可以做到这一点。
然而,尽管我尝试了很多,但我无法将 View 的属性绑定(bind)到 Windows Phone 上的 ModelView。我总是收到 空引用异常 .
我最接近的是下面的代码,包括来自 ReSharper 的建议。这是我的 FirstView.xaml.cs:
using Cirrious.MvvmCross.Binding.BindingContext;
using Whatever.ViewModels;
namespace Whatever {
// inheriting from IMvxBindingContextOwner was suggested by ReSharper also
public partial class FirstView : BaseView, IMvxBindingContextOwner {
public class MyBindableMediaElement
{
private string _theMediaSource = "whatever";
public string TheMediaSource
{
get
{
return _theMediaSource;
}
set
{
_theMediaSource = value;
}
}
}
public FirstView()
{
InitializeComponent();
_mediaElement = new MyBindableMediaElement(this.theMediaElement);
var set = this.CreateBindingSet<FirstView, FirstViewModel>();
// the corresponding view model has a .SongToPlay property with get/set defined
set.Bind(_mediaElement).For(v => v.TheMediaSource).To(vm => vm.SongToPlay);
set.Apply();
}
public IMvxBindingContext BindingContext { get; set; } // this was suggested by ReSharper
}
创建 View 后,我会在 MvxBaseFluentBindingDescription.cs 中收到 NullReferenceException。具体位置如下:
protected static string TargetPropertyName(Expression<Func<TTarget, object>> targetPropertyPath)
{
var parser = MvxBindingSingletonCache.Instance.PropertyExpressionParser; // <----- exception here**
var targetPropertyName = parser.Parse(targetPropertyPath).Print();
return targetPropertyName;
}
我还没有看到在 Windows Phone 模拟器上创建绑定(bind)集的工作示例。有没有人让这个工作?谢谢。
最佳答案
我可以确认叙述者说这句话有点太轻率了,没有真正考虑过他会怎么做……
但是,只要稍加努力,您绝对可以让 CreateBindingSet 在 Windows 中工作,如果您愿意的话。
在开始之前,请考虑一些替代方案 - 特别是,我怀疑大多数人会使用 Windows DependencyProperty 绑定(bind)或一些带有 PropertyChanged 事件订阅的手工代码隐藏。
如果您确实想将 CreateBindingSet 代码添加到 Windows 项目中,那么:
DoRegistration
在那个 builder 身上。前两个步骤都包含在 n=35 西藏绑定(bind)视频中 - 第二步将初始化绑定(bind)框架并帮助您克服当前的“NullReferenceException”(有关代码,请参阅 BindMe.Store/Setup.cs)BindingContext = new MvxBindingContext();
一样简单地做到这一点。 BindingContext.DataContext = this.ViewModel;
到您电话页面的 OnNavigatedTo
末尾方法。如果您也打算在其他类中使用 Mvx Binding,则步骤 3 和 4 都可以在您的 BaseView 中进行。 new MvxBindingContext()
之后完成。已经被创造了。 我现在没有一台 Windows 机器,所以我担心这个答案代码未经测试 - 如果它有效或无效,请再次发布。
关于mvvmcross - 如何在 Windows Phone 上执行 CreateBindingSet()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18115240/