Xamarin表单 - BindableProperty不工作

时间:2017-07-21 04:55:06

标签: c# binding uwp xamarin.forms

我们的系统中有几个BindableProperties。他们大部分都在工作,我以前也没遇到过这个问题。我正在测试UWP,但问题在其他平台上可能是相同的。

你可以在这里看到下载这段代码,看看我在说什么 https://ChristianFindlay@bitbucket.org/ChristianFindlay/xamarin-forms-scratch.git

这是我的代码:

public class ExtendedEntry : Entry
{
    public static readonly BindableProperty TestProperty =
      BindableProperty.Create<ExtendedEntry, int>
      (
      p => p.Test,
      0,
      BindingMode.TwoWay,
      propertyChanging: TestChanging
      );

    public int Test
    {
        get
        {
            return (int)GetValue(TestProperty);
        }
        set
        {
            SetValue(TestProperty, value);
        }
    }

    private static void TestChanging(BindableObject bindable, int oldValue, int newValue)
    {
        var ctrl = (ExtendedEntry)bindable;
        ctrl.Test = newValue;
    }
}

这是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:TestXamarinForms"
             x:Class="TestXamarinForms.BindablePropertyPage">
    <ContentPage.Content>
        <StackLayout>
            <local:ExtendedEntry Test="1" />
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

我可以看到,在Test的setter中,1被传递给SetValue。但是,在下一行中,我在Watch窗口中查看属性的GetValue,值为0.BindableProperty并不坚持。我尝试使用一些不同的Create重载来实例化BindingProperty,但似乎没有任何效果。我做错了什么?

1 个答案:

答案 0 :(得分:0)

对于初学者,您使用的BindableProperty.Create方法已被弃用,我建议您更改它。此外,我认为您应该使用propertyChanged:代替propertyChanging:例如:

public static readonly BindableProperty TestProperty = BindableProperty.Create(nameof(Test), typeof(int), typeof(ExtendedEntry), 0, BindingMode.TwoWay, propertyChanged: TestChanging);

public int Test
{
    get { return (int)GetValue(TestProperty); }
    set { SetValue(TestProperty, value); }
}

private static void TestChanging(BindableObject bindable, object oldValue, object newValue)
{
    var ctrl = (ExtendedEntry)bindable;
    ctrl.Test = (int)newValue;
}