【问题标题】:Xamarin Forms - BindableProperty Not WorkingXamarin 表单 - BindableProperty 不起作用
【发布时间】:2017-12-27 00:12:17
【问题描述】:

我们的系统中有几个 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。但是,在下一行中,我查看了监视窗口中属性的 GetValue 和值 0。 BindableProperty 没有粘住。我尝试使用一些不同的 Create 重载实例化 BindingProperty,但似乎没有任何效果。我做错了什么?

【问题讨论】:

    标签: c# binding uwp xamarin.forms


    【解决方案1】:

    对于初学者,您使用的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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-21
      • 1970-01-01
      • 2018-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-26
      • 2017-09-19
      相关资源
      最近更新 更多