如何将命令绑定到 Xamarin Forms 中的 Entry "Unfocused" 事件
How to bind a command to Entry "Unfocused" event in Xamarin Forms
我有一个命令(或一段代码),我想在特定条目失去焦点时 运行。
我正在使用 MVVM,所以我想使用绑定方式而不是在 Form.xaml.cs
中编写代码。
当我的条目在 XAML
文件中失去焦点时,我如何才能使我的命令(或我的代码)运行?
在 Xamarin.Forms 个样本 (see here) 中有一个 EventToCommandBehavior
的例子。使用这个你可以绑定你的控件
<Entry>
<Entry.Behaviors>
<behaviors:EventToCommandBehavior
EventName="Unfocused"
Command="{Binding EntryUnfocused}" />
</Entry.Behaviors>
</Entry>
然后在您的特定视图的 class 或 viewmodel.cs
文件中定义 EntryUnfocused
,如下所示:
public class LoginViewModel : XamarinViewModel
{
public ICommand EntryUnfocused{ get; protected set; }
public LoginViewModel()
{
EntryUnfocused= new Command(CompletedCommandExecutedAsync);
}
private void CompletedCommandExecutedAsync(object param)
{
//yourcode...
}
}
如果你使用的是 Prism 库,你可以使用他们的实现,它更成熟一点(允许你通过指定映射事件参数,传递哪个参数),see here.
(请注意 您必须将行为所在的相应命名空间添加到您的 XAML 文件中。
如果您使用 Xamarin Community Toolkit,您可以使用已经存在的 EventToCommandBehavior
。
使用这个将与 Paul Kertscher 的回答相同。
加入你的控制header:
xmlns:toolkit="http://xamarin.com/schemas/2020/toolkit"
在您的 Entry
绑定到命令:
<Entry.Behaviors>
<toolkit:EventToCommandBehavior
EventName="Unfocused"
Command="{Binding EntryUnfocused}" />
</Entry.Behaviors>
我有一个命令(或一段代码),我想在特定条目失去焦点时 运行。
我正在使用 MVVM,所以我想使用绑定方式而不是在 Form.xaml.cs
中编写代码。
当我的条目在 XAML
文件中失去焦点时,我如何才能使我的命令(或我的代码)运行?
在 Xamarin.Forms 个样本 (see here) 中有一个 EventToCommandBehavior
的例子。使用这个你可以绑定你的控件
<Entry>
<Entry.Behaviors>
<behaviors:EventToCommandBehavior
EventName="Unfocused"
Command="{Binding EntryUnfocused}" />
</Entry.Behaviors>
</Entry>
然后在您的特定视图的 class 或 viewmodel.cs
文件中定义 EntryUnfocused
,如下所示:
public class LoginViewModel : XamarinViewModel
{
public ICommand EntryUnfocused{ get; protected set; }
public LoginViewModel()
{
EntryUnfocused= new Command(CompletedCommandExecutedAsync);
}
private void CompletedCommandExecutedAsync(object param)
{
//yourcode...
}
}
如果你使用的是 Prism 库,你可以使用他们的实现,它更成熟一点(允许你通过指定映射事件参数,传递哪个参数),see here.
(请注意 您必须将行为所在的相应命名空间添加到您的 XAML 文件中。
如果您使用 Xamarin Community Toolkit,您可以使用已经存在的 EventToCommandBehavior
。
使用这个将与 Paul Kertscher 的回答相同。
加入你的控制header:
xmlns:toolkit="http://xamarin.com/schemas/2020/toolkit"
在您的 Entry
绑定到命令:
<Entry.Behaviors>
<toolkit:EventToCommandBehavior
EventName="Unfocused"
Command="{Binding EntryUnfocused}" />
</Entry.Behaviors>