question

JanDuldhardt-0002 avatar image
0 Votes"
JanDuldhardt-0002 asked JessieZhang-2116 answered

How to Attach behavior to entry in custom control

Hey so what I am trying to do is to create a custom control which is not more than a content view with an entry and a label. Now in my page.xaml I would like to use that custom control and also attach a behavior to the entry of the custom control.

<CustomControl Title="double entry" >
<CustomControl.Entry.Behavior>
// Attach behaviors
</>

I don't want to define the behaviors in the custom control because the behavior will be page specific.

dotnet-xamarin
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

JessieZhang-2116 avatar image
0 Votes"
JessieZhang-2116 answered

Hello,


Welcome to our Microsoft Q&A platform!

You can try to create a Xamarin.Forms Behavior for your custom control.

You can refer to the following code:

 public class NumericValidationBehavior : Behavior<Entry>
 {
     protected override void OnAttachedTo(Entry entry)
     {
         entry.TextChanged += OnEntryTextChanged;
         base.OnAttachedTo(entry);
     }
    
     protected override void OnDetachingFrom(Entry entry)
     {
         entry.TextChanged -= OnEntryTextChanged;
         base.OnDetachingFrom(entry);
     }
    
     void OnEntryTextChanged(object sender, TextChangedEventArgs args)
     {
         double result;
         bool isValid = double.TryParse (args.NewTextValue, out result);
         ((Entry)sender).TextColor = isValid ? Color.Default : Color.Red;
     }
 }

For more details, you can refer official document : https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/behaviors/creating



Best Regards,


Jessie Zhang


If the response is helpful, please click "Accept Answer" and upvote it.



Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.