Это мое поле сообщения. В настоящее время я могу ввести сообщение здесь. Если я щелкну по следующему полю или за пределами поля ввода, курсор должен расфокусироваться. Мне нужно добиться такого поведения. Если кто-нибудь знает, как решить эту проблему в .NET MAUI, укажите каждый шаг реализации.
XML:
<!-- Message Field -->
<Grid.GestureRecognizers>
<!-- Adding a Tap Gesture Recognizer to the Grid to handle taps outside the note editor -->
<TapGestureRecognizer Command = "{Binding TapOutsideNoteCommand}" />
</Grid.GestureRecognizers>
<!-- Label indicating the purpose of the note entry -->
<Label Grid.Row = "7" Grid.Column = "0" Grid.ColumnSpan = "2" Margin = "0,20,0,0"
TextColor = "{StaticResource White}" Text = "Add a note"
FontSize = "16" FontFamily = "Roboto-Medium" IsVisible = "{Binding IsMessageVisible}" />
<!-- Border to contain the note editor and character count label -->
<Border Grid.Row = "8" Background = "White" Grid.ColumnSpan = "3" Margin = "0,10,0,0"
StrokeThickness = "0" StrokeShape = "RoundRectangle 5" IsVisible = "{Binding IsMessageVisible}">
<!-- StackLayout to contain the note editor and character count label -->
<StackLayout HorizontalOptions = "Fill" VerticalOptions = "Fill" BackgroundColor = "Transparent">
<!-- Custom editor for entering the note -->
<controls:CustomEditor x:Name = "noteEditor" Margin = "10,10,10,5" BackgroundColor = "Transparent" AutoSize = "TextChanges"
Text = "{Binding Message}" TextColor = "Black" Placeholder = "Enter your note here"
FontSize = "15" FontFamily = "Roboto-Regular" IsReadOnly = "{Binding IsMessageReadOnly}"
HorizontalOptions = "Fill" VerticalOptions = "Fill" IsFocused = "{Binding IsNoteEditorFocused}" />
<!-- Label to display character count -->
<Label x:Name = "characterCountLabel" Margin = "0,0,10,5" Text = "100 Character" TextColor = "{StaticResource Gray600}"
FontSize = "14" FontFamily = "Roboto-Light" HorizontalOptions = "End"/>
</StackLayout>
</Border>
Модель просмотра:
// Boolean property to track the focus state of the note editor
private bool _isNoteEditorFocused;
public bool IsNoteEditorFocused
{
get => _isNoteEditorFocused;
set
{
if (_isNoteEditorFocused != value)
{
_isNoteEditorFocused = value;
NotifyPropertyChanged(nameof(IsNoteEditorFocused));
}
}
}
// Command to handle taps outside the note editor
public ICommand TapOutsideNoteCommand { get; private set; }
// Constructor to initialize the TapOutsideNoteCommand
public YourViewModelConstructor()
{
TapOutsideNoteCommand = new Command(OnTapOutsideNote);
}
// Method to unfocus the note editor when tapped outside
private void OnTapOutsideNote()
{
IsNoteEditorFocused = false;
}
Что конкретно не работает с вашим кодом?





Вы можете проверить эту тему в этой теме Невозможно расфокусировать запись, а HideSoftInputOnTapped закрывает программную клавиатуру, но не удаляет фокус с записи.
Одно из решений проблемы: поместите приведенный ниже код в MAUI Android MainActivity.cs.
public override bool DispatchTouchEvent(MotionEvent? e)
{
if (e!.Action == MotionEventActions.Down)
{
var focusedElement = CurrentFocus;
if (focusedElement is EditText editText)
{
var editTextLocation = new int[2];
editText.GetLocationOnScreen(editTextLocation);
var clearTextButtonWidth = 100; // syncfusion clear button at the end of the control
var editTextRect = new Rect(editTextLocation[0], editTextLocation[1], editText.Width + clearTextButtonWidth, editText.Height);
//var editTextRect = editText.GetGlobalVisibleRect(editTextRect); //not working in MAUI, always returns 0,0,0,0
var touchPosX = (int)e.RawX;
var touchPosY = (int)e.RawY;
if (!editTextRect.Contains(touchPosX, touchPosY))
{
editText.ClearFocus();
var inputService = GetSystemService(Context.InputMethodService) as InputMethodManager;
inputService?.HideSoftInputFromWindow(editText.WindowToken, 0);
}
}
}
return base.DispatchTouchEvent(e);
}
Для Android см. этот ответ: github.com/dotnet/maui/issues/21053#issuecomment-1997163629