Reputation: 2703
I have a custom control CustomTextBox.xaml
:
<AbsoluteLayout xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MyApp.Core.Controls.CustomTextBox"
xmlns:controls="clr-namespace:MyApp.Core.Controls;assembly=MyApp.Core"
BackgroundColor="White">
<AbsoluteLayout.GestureRecognizers>
<TapGestureRecognizer Tapped="OnTapped"/>
</AbsoluteLayout.GestureRecognizers>
<Entry x:Name="textValueEntry" AbsoluteLayout.LayoutFlags="All" AbsoluteLayout.LayoutBounds="0.5, 1, 0.9, 0.9" FontAttributes="Bold"/>
<Label x:Name="placeholderLabel" AbsoluteLayout.LayoutFlags="PositionProportional" AbsoluteLayout.LayoutBounds="0.05, 0.5" FontSize="18"/>
</AbsoluteLayout>
I want to be able to bind to the textValueEntry
control from the parent view. So I added a bindable property in CustomTextBox.xaml.cs
:
private string _textValue;
public string TextValue
{
get
{
return _textValue;
}
set
{
_textValue = value;
}
}
public static BindableProperty TextValueProperty = BindableProperty.Create(nameof(TextValue), typeof(string), typeof(CustomTextBox), string.Empty, BindingMode.TwoWay, null,
(bindable, oldValue, newValue) =>
{
(bindable as CustomTextBox).textValueEntry.Text = (string)newValue;
});
I try to bind to it from the parent view like this:
<controls:CustomTextBox HorizontalOptions="FillAndExpand" VerticalOptions="CenterAndExpand" HeightRequest="50" TextValue="{Binding UsernamePropertyInViewModel, Mode=TwoWay}"/>
TextValue
property gets set with UsernamePropertyInViewModel
when I launch the app, as I can see it in textValueEntry
. But when I change the text in textValueEntry
it doesn't update UsernamePropertyInViewModel
. How can I bind to it so it updates UsernamePropertyInViewModel
when I change the text in textValueEntry
?
Upvotes: 0
Views: 132
Reputation: 687
As far as I can tell your CustomTextBox
entry textValueEntry
doesn't Bind to your TextValue property.
Also your TextValue
property needs to look like this for BindableProperties
. You need to set your BindableProperty to the appropriate value for a Binding. No need for a private backing variable to TextValue
.
public string TextValue
{
get => (string)GetValue(TextValueProperty);
set => SetValue(TextValueProperty, value);
}
Parent.Xaml
<Entry x:Name="textValueEntry" Text="{Binding Path=TextValue, Source={x:Reference Page}}" AbsoluteLayout.LayoutFlags="All" AbsoluteLayout.LayoutBounds="0.5, 1, 0.9, 0.9" FontAttributes="Bold"/>
Your Page will need an x:Name="Page" for the Binding Source
Upvotes: 1