Reputation: 7672
We have several BindableProperties in our system. They mostly work, and I haven't come across this problem before. I am testing on UWP, but the problem is probably the same on other platforms.
You can see download this code here to see exactly what I am talking about https://[email protected]/ChristianFindlay/xamarin-forms-scratch.git
Here is my code:
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;
}
}
This is the 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>
I can see that in the setter for Test, 1 is being passed in to SetValue. But, on the next line, I look at GetValue for the property in the watch window, and the value 0. The BindableProperty is not sticking. I've tried instantiating the BindingProperty with a few different Create overloads, but nothing seems to work. What am I doing wrong?
Upvotes: 4
Views: 3351
Reputation: 3251
For starters the method of BindableProperty.Create
you're using has been deprecated and I would suggest changing it. Also, I think you should be probably be using propertyChanged:
instead of propertyChanging:
For example:
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;
}
Upvotes: 1