I'm having difficulty binding my ViewModel to a custom control. On the same View, binding to a regular control works but the custom control is blank.
Here's the custom control:
public class CustomEntry : StackLayout
{
protected Entry entry;
public CustomEntry ()
{
entry = new Entry ();
Children.Add (entry);
}
public static readonly BindableProperty TextProperty=BindableProperty.Create<CustomEntry, string>( p => p.Text, "" );
public String Text {
get { return entry.Text; }
set { entry.Text = value; }
}
}
And the view:
<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="TestMVVM.TestPage"
xmlns:mv="clr-namespace:TestMVVM"
Padding="10, 20">
<ContentPage.BindingContext>
<mv:TestViewModel />
</ContentPage.BindingContext>
<StackLayout>
<Entry Text="{Binding TestValue}" />
<mv:CustomEntry Text="{Binding TestValue}" />
</StackLayout>
</ContentPage>
And the viewmodel:
public class TestViewModel : INotifyPropertyChanged
{
double testValue;
public event PropertyChangedEventHandler PropertyChanged;
public TestViewModel ()
{
var random = new Random ();
testValue = random.NextDouble ();
}
public double TestValue
{
set {
if (testValue != value) {
testValue = value;
OnPropertyChanged ("TestValue");
}
}
get {
return testValue;
}
}
protected virtual void OnPropertyChanged (string propertyName) {
if (PropertyChanged != null) {
PropertyChanged (this, new PropertyChangedEventArgs(propertyName));
}
}
}
I put the full code up on GitHub: [https://github.com/andybarilla/BindableCustomTest]