Xamarin表格Mvvm绑定失败

时间:2017-04-11 12:09:41

标签: xamarin mvvm binding xamarin.forms

我遇到了Xamarin Forms自定义控件绑定的问题。这是一些代码!

MainPage.xaml中

 <?xml version="1.0" encoding="utf-8" ?> 
 <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
           xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
           xmlns:local="clr-namespace:TestXamForms"
           x:Class="TestXamForms.MainPage">

   <local:TestControl Detail="{Binding Detail, Mode=TwoWay}"/>
 </ContentPage>

MainPage.xaml.cs中

public partial class MainPage:ContentPage
{
    public MainPage()
    {
        InitializeComponent();
    }
    protected override void OnAppearing()
    {
        base.OnAppearing();BindingContext=new MainPageVM();
    }
}
public class MainPageVM:ObservableObject
{
    public DetailModel Detail{get;set;}=new DetailModel{Name="fish"};
}

TestControl.xaml

<?xml version="1.0" encoding="UTF-8"?> 
<ContentView
  xmlns="http://xamarin.com/schemas/2014/forms"
  xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
  x:Class="TestXamForms.TestControl">
  <ContentView.Content>
    <Label Text="{Binding Detail.Name}"/>
  </ContentView.Content> 
</ContentView>

TestControl.xaml.cs

public partial class TestControl: ContentView 
{
     public static readonly BindableProperty DetailProperty = BindableProperty.Create("Detail", typeof(DetailModel), typeof(TestControl), propertyChanged: DetailPropertyChanged);

     private static void DetailPropertyChanged(BindableObject bindable, object oldValue, object newValue)
     {
         (bindable as TestControl).VM.Detail = newValue as DetailModel;
     }

     public DetailModel Detail 
     {
        get => (DetailModel) GetValue(DetailProperty);
        set => SetValue(DetailProperty, value);
     }

     private TestControlVM VM 
     {
        get => BindingContext as TestControlVM;
        set => BindingContext = value;
     }

     public TestControl() 
     {
        InitializeComponent();
        VM = new TestControlVM();
     }
}

public class TestControlVM: ObservableObject 
{
    private DetailModel _detail;

     public DetailModel Detail 
     {
        get => _detail;
        set => SetProperty(ref _detail, value);
     }
}

当更新MainPage的BindingContext时,TestControl的Detail副本不会通过Binding更新。这通常吗?如果是这样,我该如何实现呢?

0 个答案:

没有答案