绑定开关切换属性

问题描述 投票:0回答:1
c# .net mobile cross-platform maui
1个回答
0
投票

您可以使用 Maui CommunityToolkit EventToCommandBehavior.

在 xaml 中,我们将 Behaviors 添加到 Switch 中。 EventToCommandBehavior 将 Toggled 事件更改为 ToggledCommand(稍后在视图模型中定义)。

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
...
     xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit">


<Switch             
   HorizontalOptions="End" 
   VerticalOptions="Center"
   Margin="20,0"
   OnColor="#00CD00"
   ThumbColor="White"
   >
   <Switch.Behaviors>
       <toolkit:EventToCommandBehavior
           EventName="Toggled"
           Command="{Binding ToggledCommand}" />
   </Switch.Behaviors>

在 viewModel 文件中,我们定义了 ToggledCommand,

public class MainPageViewModel
{
    public Command ToggledCommand
    {
        get
        {
            return new Command(() =>
            {
                //you could add your function here                  
                Console.WriteLine("123");
            });
        }
    }

不要忘记在 MauiProgram.cs 中初始化包:

public static class MauiProgram
{
    public static MauiApp CreateMauiApp()
    {
        var builder = MauiApp.CreateBuilder();
        builder
            .UseMauiApp<App>()
            .UseMauiCommunityToolkit()
            .ConfigureFonts(fonts =>
...

希望它有效。

© www.soinside.com 2019 - 2024. All rights reserved.