嗨,我有一个使用 ContentTemplates 的毛伊岛应用程序,我试图将编辑器的 Unfocused 事件绑定到 Viewmodel 上的 RelayCommand。
我已成功将按钮单击绑定到 RelayCommand,但编辑器未聚焦命令不会触发。
仅供参考,我已经实施了以下解决方案来解决编辑器不专注于单击控件外部的问题:
https://github.com/dotnet/maui/issues/21053
这里是示例存储库,其中功能位于主页中:
非常感谢任何帮助。
使用
ContentView
时,您最好的宠物就是专注于命令或属性。如果要将事件映射到命令,则需要额外的工作,但这是可行的,但是,因为 Editor
有一个 IsFocused
属性,我们可以声明一个名为 IsEditorFocused 的 BindableProperty 并使用 OneWayBindingToSource 从编辑器通过 ContentView 到达页面:
<!-- CustomEditor.xaml -->
<ContentView
x:Class="Maui.StackOverflow.CustomEditor"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml">
<ContentView.ControlTemplate>
<ControlTemplate>
<Border>
<Editor IsFocused="{TemplateBinding IsEditorFocused, Mode=OneWayToSource}" />
</Border>
</ControlTemplate>
</ContentView.ControlTemplate>
</ContentView>
// CustomEditor.xaml.cs
namespace Maui.StackOverflow;
public partial class CustomEditor : ContentView
{
public static readonly BindableProperty IsEditorFocusedProperty = BindableProperty.Create(nameof(IsEditorFocused), typeof(bool), typeof(CustomEditor), false);
public bool IsEditorFocused
{
get => (bool)GetValue(IsFocusedProperty);
set => SetValue(IsFocusedProperty, value);
}
public CustomEditor()
{
InitializeComponent();
}
}
我们可以在页面上使用它,如下所示:
<!-- EditorPage.xaml -->
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
x:Class="Maui.StackOverflow.EditorPage"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:Maui.StackOverflow"
x:Name="thisPage"
Title="EditorPage"
x:DataType="local:EditorPage">
<VerticalStackLayout>
<Entry Text="Entry1" />
<local:CustomEditor IsFocused="{Binding IsEditorFocused, Mode=OneWayToSource, Source={Reference thisPage}}" />
<Entry Text="Entry2" />
</VerticalStackLayout>
</ContentPage>
// EditorPage.xaml.cs
using System.Diagnostics;
namespace Maui.StackOverflow;
public partial class EditorPage : ContentPage
{
public static readonly BindableProperty IsEditorFocusedProperty = BindableProperty.Create(nameof(IsEditorFocused), typeof(bool), typeof(EditorPage), false);
public bool IsEditorFocused
{
get => (bool)GetValue(IsEditorFocusedProperty);
set => SetValue(IsEditorFocusedProperty, value);
}
public EditorPage()
{
InitializeComponent();
BindingContext = this;
PropertyChanged += (s, e) =>
{
switch (e.PropertyName)
{
case nameof(IsEditorFocused):
Debug.WriteLine($"IsEditorFocused changed to {IsEditorFocused}");
break;
}
};
}
}