如何在Windows Phone 8上进行代码内绑定

3
我正在尝试在Windows Phone 8上进行代码绑定,就像问题“How to do CreateBindingSet() on Windows Phone?”中所述。How to do CreateBindingSet() on Windows Phone? 我认为我已经按照Stuart的建议完成了步骤,但我一直收到异常错误或输出错误“MvxBind:Warning: 9,86 Failed to create target binding for binding _update for TextUpdate”。在Droid中它运行得非常好,那么我做错了什么,缺少了什么或者没有看到什么?有什么建议吗?我在电话部分有以下设置。

Setup.cs:

using Cirrious.CrossCore.Platform;
using Cirrious.MvvmCross.BindingEx.WindowsShared;
using Cirrious.MvvmCross.ViewModels;
using Cirrious.MvvmCross.WindowsPhone.Platform;
using Microsoft.Phone.Controls;

namespace DCS.Phone
{
    public class Setup : MvxPhoneSetup
    {
        public Setup(PhoneApplicationFrame rootFrame) : base(rootFrame)
        {
        }

        protected override IMvxApplication CreateApp()
        {
            return new Core.App();
        }

        protected override IMvxTrace CreateDebugTrace()
        {
            return new DebugTrace();
        }

        protected override void InitializeLastChance()
        {
            base.InitializeLastChance();

            var builder = new MvxWindowsBindingBuilder();
            builder.DoRegistration();
        }
    }
}

ServerView.xaml:

<views:MvxPhonePage
    x:Class="DCS.Phone.Views.ServerView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:views="clr-namespace:Cirrious.MvvmCross.WindowsPhone.Views;assembly=Cirrious.MvvmCross.WindowsPhone"
    xmlns:converters="clr-namespace:DCS.Phone.Converters"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    mc:Ignorable="d"
    shell:SystemTray.IsVisible="True">

    <!--LayoutRoot is the root grid where all page content is placed-->

  <Grid x:Name="LayoutRoot" Background="Transparent">
    <!--used as dummy bool to call Update callback through converter -->
    <CheckBox x:Name ="DummyUpdated" Height ="0" Width ="0"  Content="" Visibility="Visible" IsChecked="{Binding TextUpdate, Converter={StaticResource Update }, ConverterParameter=ServerView}"></CheckBox>
    <ScrollViewer x:Name="ScrollView" Height="760" Width ="480" VerticalAlignment="Top">
         <Canvas x:Name="View" Top="0" Left="0" Margin ="0" Background="Transparent" Height="Auto" Width ="Auto"/>
    </ScrollViewer>
  </Grid>
</views:MvxPhonePage>

ServerView.xaml.cs:

using System.Windows;
using Cirrious.MvvmCross.Binding.BindingContext;
using Cirrious.MvvmCross.WindowsPhone.Views;
using DCS.Core;
using DCS.Core.ViewModels;
using DCS.Phone.Controls;

namespace DCS.Phone.Views
{
    public partial class ServerView : MvxPhonePage,IMvxBindingContextOwner
    {
        private bool _isUpdating;
        private bool _update;
        private DcsText _text;
        private DcsInput _input;
        private DcsList _list;
        private DcsButton _button;

        public IMvxBindingContext BindingContext { get; set; }

        public ServerView(){
            InitializeComponent();
            BindingContext = new MvxBindingContext();            
            Loaded += new RoutedEventHandler(MainPage_Loaded);
        }

        private void MainPage_Loaded(object sender, RoutedEventArgs e){
            CreateControls();
        }
        private void CreateControls() {
            //User controls
            _text = new DcsText(View);
            _input = new DcsInput(View, View, DummyUpdated);
            _list = new DcsList(View);
            _button = new DcsButton(View);

            //Bindings
            var set = this.CreateBindingSet<ServerView, ServerViewModel>();
            set.Bind(this).For(v => v._update).To(vm => vm.TextUpdate).OneWay().WithConversion("Update", this);
            for (int i = 0; i < Constants.MaxButton; i++){
              set.Bind(_button.Button[i]).To(vm => vm.ButtonCommand).CommandParameter(i);
            }
            set.Apply();
            AppTrace.Trace(string.Format("OnCreate Finish"));
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e){
            base.OnNavigatedTo(e);
            BindingContext.DataContext = this.ViewModel;
       }
    } 
}

我尝试执行 set.Apply() 时出现以下错误:
set.Apply() 异常。
var set = this.CreateBindingSet<ServerView, ServerViewModel>();
for (int i = 0; i < Constants.MaxButton; i++){
  set.Bind(_button.Button[i]).To(vm => vm.ButtonCommand).CommandParameter(i);
}
set.Apply();

System.NullReferenceException was unhandled by user code
  HResult=-2147467261
  Message=Object reference not set to an instance of an object.
  Source=Cirrious.MvvmCross.BindingEx.WindowsPhone
  StackTrace:
       at Cirrious.MvvmCross.BindingEx.WindowsShared.MvxDependencyPropertyExtensionMethods.EnsureIsDependencyPropertyName(String& dependencyPropertyName)
       at Cirrious.MvvmCross.BindingEx.WindowsShared.MvxDependencyPropertyExtensionMethods.FindDependencyPropertyInfo(Type type, String dependencyPropertyName)
       at Cirrious.MvvmCross.BindingEx.WindowsShared.MvxDependencyPropertyExtensionMethods.FindDependencyProperty(Type type, String name)
       at Cirrious.MvvmCross.BindingEx.WindowsShared.MvxBinding.MvxWindowsTargetBindingFactoryRegistry.TryCreatePropertyDependencyBasedBinding(Object target, String targetName, IMvxTargetBinding& binding)
       at Cirrious.MvvmCross.BindingEx.WindowsShared.MvxBinding.MvxWindowsTargetBindingFactoryRegistry.TryCreateReflectionBasedBinding(Object target, String targetName, IMvxTargetBinding& binding)
       at Cirrious.MvvmCross.Binding.Bindings.Target.Construction.MvxTargetBindingFactoryRegistry.CreateBinding(Object target, String targetName)
       at Cirrious.MvvmCross.Binding.Bindings.MvxFullBinding.CreateTargetBinding(Object target)
       at Cirrious.MvvmCross.Binding.Bindings.MvxFullBinding..ctor(MvxBindingRequest bindingRequest)
       at Cirrious.MvvmCross.Binding.Binders.MvxFromTextBinder.BindSingle(MvxBindingRequest bindingRequest)
       at Cirrious.MvvmCross.Binding.Binders.MvxFromTextBinder.<>c__DisplayClass1.<Bind>b__0(MvxBindingDescription description)
       at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
       at Cirrious.MvvmCross.Binding.BindingContext.MvxBindingContextOwnerExtensions.AddBindings(IMvxBindingContextOwner view, IEnumerable`1 bindings, Object clearKey)
       at Cirrious.MvvmCross.Binding.BindingContext.MvxBindingContextOwnerExtensions.AddBindings(IMvxBindingContextOwner view, Object target, IEnumerable`1 bindingDescriptions, Object clearKey)
       at Cirrious.MvvmCross.Binding.BindingContext.MvxBindingContextOwnerExtensions.AddBinding(IMvxBindingContextOwner view, Object target, MvxBindingDescription bindingDescription, Object clearKey)
       at Cirrious.MvvmCross.Binding.BindingContext.MvxBaseFluentBindingDescription`1.Apply()
       at Cirrious.MvvmCross.Binding.BindingContext.MvxFluentBindingDescriptionSet`2.Apply()
       at DCS.Phone.Views.ServerView.CreateControls()
       at DCS.Phone.Views.ServerView.MainPage_Loaded(Object sender, RoutedEventArgs e)
       at MS.Internal.CoreInvokeHandler.InvokeEventHandler(Int32 typeIndex, Delegate handlerDelegate, Object sender, Object args)
       at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, Int32 actualArgsTypeIndex, String eventName)
  InnerException: 

set.Apply()的输出;
var set = this.CreateBindingSet<ServerView, ServerViewModel>();
set.Bind(this).For(v => v._update).To(vm => vm.TextUpdate).OneWay().WithConversion("Update", this);
set.Apply();

MvxBind:Warning:  9,86 Failed to create target binding for binding _update for TextUpdate

只是为了澄清。
set.Bind(this).For(v => v._update).To(vm => vm.TextUpdate).OneWay().WithConversion("Update", this);

在设置中使用了Apply()函数并发出了警告。
MvxBind:Warning:  9,86 Failed to create target binding for binding _update for TextUpdate

“使用公共布尔值Update确实解决了set.Apply()的问题,但我没有得到绑定。”
“在Droid中,所有这些都可以工作。”
set.Bind(this).For("_update").To(vm => vm.TextUpdate).OneWay().WithConversion("Update", this);
set.Bind("_update").To(vm => vm.TextUpdate).OneWay().WithConversion("Update", this);
set.Bind(this).For(v=>v._update).To(vm => vm.TextUpdate).OneWay().WithConversion("Update", this);
set.Bind(this).For(v=>v.Update).To(vm => vm.TextUpdate).OneWay().WithConversion("Update", this);
set.Bind("Update").To(vm => vm.TextUpdate).OneWay().WithConversion("Update", this); 

这段代码的意思是:将_button.Button[i]绑定到vm.ButtonCommand,并设置命令参数为i。但出现了异常。
1个回答

3

从堆栈跟踪来看,代码在以下位置失败:https://github.com/MvvmCross/MvvmCross/blob/v3.1/Cirrious/Cirrious.MvvmCross.BindingEx.WindowsPhone/MvxDependencyPropertyExtensionMethods.cs#L113

    private static void EnsureIsDependencyPropertyName(ref string dependencyPropertyName)
    {
        if (!dependencyPropertyName.EndsWith("Property"))
            dependencyPropertyName += "Property";
    }

这表明传递给该方法的dependencyPropertyName名称为null
我的猜测是因为_update既不是属性也不是public。MvvmCross绑定仅适用于属性,而.Net安全性只允许其与public一起使用(尽管您可以使用internal和一些assembly:InternalsVisibleTo代码)。
尝试将_update替换为具有get和set访问权限的public属性,例如:
  public bool Update {
      get { return _update; }
      set { _update = value; /* do something with the new value? */ }
  }

使用:

 set.Bind(this).For(v => v.Update).To(vm => vm.TextUpdate).OneWay().WithConversion("Update", this);

附注:在非Windows绑定中,此问题将导致更好的错误消息 - 来自https://github.com/MvvmCross/MvvmCross/blob/v3.1/Cirrious/Cirrious.MvvmCross.Binding/Bindings/Target/Construction/MvxTargetBindingFactoryRegistry.cs#L34Empty binding target passed to MvxTargetBindingFactoryRegistry。我们也会把这个问题放在Windows的待办事项列表中。


仅澄清一下。 'set.Bind(this).For(v => v._update).To(vm => vm.TextUpdate).OneWay().WithConversion("Update", this);' 在set.Apply()上发出警告。MvxBind:Warning: 9,86 Failed to create target binding for binding _update for TextUpdate使用公共布尔值Update解决了set.Apply()问题,但我没有得到绑定。'set.Bind(_button.Button[i]).To(vm => vm.ButtonCommand).CommandParameter(i);'引发了异常: - user2831196

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