1
I created a Customcontrol but creating a Bindingproperty I cannot perform a Binding
Custom Control XAML code
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="CustomControls.Controls.CustomEditor">
<Editor x:Name="edt" Text="{Binding Text, Mode=TwoWay}" />
</ContentView>
CS code of Customcontrol
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class CustomEditor : ContentView
{
public CustomEditor ()
{
InitializeComponent ();
this.BindingContext = this;
}
public static readonly BindableProperty TextProperty = BindableProperty.Create(
propertyName: nameof(Text),
returnType: typeof(string),
declaringType: typeof(CustomEditor),
defaultValue: "",
defaultBindingMode: BindingMode.TwoWay,
propertyChanged: (b, o, n) =>
{
if (b is CustomEditor view)
view.edt.Text = n.ToString();
});
public string Text
{
get => (string)GetValue(TextProperty);
set
{
SetValue(TextProperty, value);
base.OnPropertyChanged(nameof(Text));
}
}
}
Mainpage XAML that consumes Customcontrol
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:CustomControls"
xmlns:controls="clr-namespace:CustomControls.Controls"
x:Class="CustomControls.MainPage">
<StackLayout Padding="10">
<Label Text="{Binding Email}"/>
<Editor x:Name="txtTeste" Text="{Binding Email}"/>
<controls:CustomEditor Text="{Binding Email, Mode=TwoWay}"/>
</StackLayout>
</ContentPage>
Mainpage CS
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
BindingContext = this;
this.Email = "[email protected]";
}
private string _email;
public string Email
{
get { return _email; }
set { _email = value; base.OnPropertyChanged(nameof(Email)); }
}
}
In Mainpage in customControl if I start with a Hardcode it already opens the app with Editor filled but any change in the property Email it does not reflect in the Editor and if I change the value of the Editor it does not reflect in the property email, it is possible to use Binding in this Situation?