我正在尝试将可绑定属性添加到 Xamarin.Forms 中的条目。这应该允许我通过为 HasFocus 属性分配一个布尔值来设置/取消设置 Entry 的键盘焦点。我使用 ReactiveUI 作为 MVVM 框架,并且 RaiseAndSetIfChanged 方法隐式引发 INotifyPropertyChanged 事件(在许多其他地方都有效)。
我无法在我的 FocusedEntry 课程中遇到任何断点,也没有看到键盘出现。我错过了什么?
// XAML
<controls:FocusedEntry Text="My custom Entry"
HasFocus="{Binding EntryHasFocus, Mode=TwoWay}"/>
// View Model
private bool _entryHasFocus;
public bool EntryHasFocus
{
get => _entryHasFocus;
private set => this.RaiseAndSetIfChanged(ref _entryHasFocus, value);
}
// Custom View
public class FocusedEntry : Entry
{
public static readonly BindableProperty HasFocusProperty = BindableProperty.Create(
nameof(HasFocus), typeof(bool), typeof(FocusedEntry), false, BindingMode.TwoWay, propertyChanged: OnHasFocusedChanged);
public bool HasFocus
{
get => (bool)GetValue(HasFocusProperty);
set => SetValue(HasFocusProperty, value);
}
private static void OnHasFocusedChanged(BindableObject bindable, object oldValue, object newValue)
{
if (bindable is FocusedEntry entry)
{
bool hasFocus = (bool)newValue;
bool wasFocused = (bool)oldValue;
if (hasFocus == wasFocused) return;
if (hasFocus)
entry.Focus();
else
entry.Unfocus();
}
}
}