在.net MAUI MVVM 中创建自定义方形复选框控件

问题描述 投票:0回答:1

这就是让我发疯的事情! 我只是找不到为 CheckBox 组件创建自定义控件的方法。当 IsChecked = false/true 时,我需要 Android 和 iOS 工作组件看起来像这样。

对于 RadioButton 来说,它相当简单,但对于 CheckBox 来说则不然。我不是 MAUI 方面的专家,并且对 C# 的了解“有限”。但我确实创建了一个自定义组件,例如 CustomDatePicker、CustomUnderlinedEntry、CustomRadioButton...

我想做这样的事情:

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:local="clr-namespace:BlaNamespace"
         x:Class="BlaNamespace.YourPage"> 

<StackLayout>
    <local:SquareCheckBox x:Name="MyCheckBox" />
    <BoxView WidthRequest="20" HeightRequest="20" 
             BorderColor="Black" BorderThickness="1"
             BackgroundColor="{Binding Source={x:Reference MyCheckBox}, Path=IsChecked, Converter={StaticResource BoolToColorConverter}}" />
</StackLayout>

但是我需要 CheckBox 的功能!

c# .net xamarin mvvm maui
1个回答
0
投票

首先,您需要为自定义复选框创建一个新类。该类应继承自 ContentView 或其他适当的 MAUI 控件。

using Microsoft.Maui.Controls;

namespace BlaNamespace
{
    public class CustomCheckBox : ContentView
    {
        private readonly BoxView checkBox;
    public static readonly BindableProperty IsCheckedProperty =
        BindableProperty.Create(nameof(IsChecked), typeof(bool), typeof(CustomCheckBox), false, propertyChanged: OnIsCheckedChanged);

    public bool IsChecked
    {
        get => (bool)GetValue(IsCheckedProperty);
        set => SetValue(IsCheckedProperty, value);
    }

    public CustomCheckBox()
    {
        checkBox = new BoxView
        {
            WidthRequest = 20,
            HeightRequest = 20,
            BorderColor = Color.Black,
            BorderThickness = 1
        };

        checkBox.GestureRecognizers.Add(new TapGestureRecognizer
        {
            Command = new Command(() => IsChecked = !IsChecked)
        });

        Content = checkBox;
    }

    private static void OnIsCheckedChanged(BindableObject bindable, object oldValue, object newValue)
    {
        var checkBox = (CustomCheckBox)bindable;
        checkBox.checkBox.BackgroundColor = (bool)newValue ? Color.Green : Color.Red;
    }
}
}

在 XAML 文件中,您现在可以使用 CustomCheckBox 控件。

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:local="clr-namespace:BlaNamespace"
         x:Class="BlaNamespace.YourPage">

<StackLayout>
    <local:CustomCheckBox x:Name="MyCheckBox" />
    <Label Text="My CheckBox" />
</StackLayout>
© www.soinside.com 2019 - 2024. All rights reserved.