[英]2 radio button group do not work in MAUI using community toolkit MVVM
我正在使用 .NET MAUI,我遇到了一個問題,我有 2 個不同的無線電組,每個無線電組都有一個使用綁定到 bool 變量的選擇。 我正在利用 NET 社區工具包 MVVM 進行綁定。 問題是當我顯示這 2 個組時,所選值只出現在其中一個上,而不是兩個上。 我測試了綁定是否對每個都有效,並且確實有效(通過一次刪除一個無線電組)。 我很困惑,我確實知道問題出在哪里。 這是我的代碼
主頁的代碼
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MauiApp1.MainPage">
<ScrollView>
<VerticalStackLayout
Spacing="25"
Padding="30,0"
VerticalOptions="Center">
<Label Text="ok"/>
<StackLayout >
<Grid ColumnDefinitions="*,*" WidthRequest="200" >
<RadioButton Grid.Column="0" Content="Yes" IsChecked="{Binding VariableA}"/>
<RadioButton Grid.Column="1" Content="No" />
</Grid>
</StackLayout >
<StackLayout >
<Grid ColumnDefinitions="*,*" WidthRequest="200" >
<RadioButton Grid.Column="0" Content="Yes" IsChecked="{Binding VariableB}"/>
<RadioButton Grid.Column="1" Content="No" />
</Grid>
</StackLayout>
</VerticalStackLayout>
</ScrollView>
</ContentPage>
主頁的代碼隱藏
namespace MauiApp1;
public partial class MainPage : ContentPage
{
public MainPage(Class1 viewModel)
{
BindingContext = viewModel;
InitializeComponent();
}
}
視圖模型的代碼
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MauiApp1
{
public partial class Class1 : ObservableObject
{
[ObservableProperty]
public bool variableA= true;
[ObservableProperty]
public bool variableB= true;
}
}
最后是 MauiProgram.cs
namespace MauiApp1;
public static class MauiProgram
{
public static MauiApp CreateMauiApp()
{
var builder = MauiApp.CreateBuilder();
builder
.UseMauiApp<App>()
.ConfigureFonts(fonts =>
{
fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
});
builder.Services.AddSingleton<MainPage>();
builder.Services.AddSingleton<Class1>();
return builder.Build();
}
}
這是我按上面編碼運行 2 radiogroup 時的結果。 你能幫我理解我做錯了什么嗎?
[如您所見,只有一個無線電組顯示我運行應用程序時選擇的值][1] [1]:https://i.stack.imgur.com/8dXP1.png
要將 Radiobuttons 添加到同一組,您需要為最上層的單選組提供組名
文件說:
RadioButtonGroup 類定義了一個 GroupName 附加屬性,類型為字符串,可以在Layout<View>
對象上設置。 這使得任何布局都可以變成單選按鈕組:
XAML
<StackLayout RadioButtonGroup.GroupName="colors">
<Label Text="What's your favourite colour?" />
<RadioButton Content="Red" />
<RadioButton Content="Green" />
<RadioButton Content="Blue" />
<RadioButton Content="Other" />
</StackLayout>
在此示例中,StackLayout 中的每個 RadioButton 都將其 GroupName 屬性設置為顏色,並且相互排斥。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.