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

我正在尝试在Windows Phone 8上执行代码内绑定,例如“如何在Windows Phone上执行CreateBindingSet()?”这样的问题.How to do CreateBindingSet() on Windows Phone?我想我已经按照Stuart的建议完成了步骤,但是我不断...

我正在尝试在Windows Phone 8上执行代码内绑定,例如“如何在Windows Phone上执行CreateBindingSet()?”这样的问题.
How to do CreateBindingSet() on Windows Phone?
我想我已经按照Stuart的建议完成了步骤,但是我不断收到异常错误或输出错误
“ MvxBind:警告:9,86无法创建用于绑定_update的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);

在set.Apply()上发出警告

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

使用公共布尔更新确实解决了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); 

set.Bind(_button.Button [i]).To(vm => vm.ButtonCommand).CommandParameter(i);

给出了例外:

解决方法:

查看堆栈跟踪,代码失败: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不是属性,也不是公共的. MvvmCross绑定适用于属性-并且.Net安全性强制它仅与public一起使用(尽管您可以通过一些汇编使用Internal:InternalsVisibleTo代码).

尝试将_update替换为同时具有get和set访问权限的公共属性-例如:

  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#L34传递到MvxTargetBindingFactoryRegistry-也会放在Windows的待办事项列表中.

本文标题为:c#-如何在Windows Phone 8上进行代码内绑定

基础教程推荐