.NET MAUI自定义Checkbox绑定VM属性不更新问题排查
自定义MAUI CheckBox双向绑定失效问题解决
问题场景
自定义MAUI CheckBox控件时,已创建IsChecked可绑定属性,但勾选UI中的CheckBox时,ViewModel(VM)中的ReverseScoring可观察属性无法同步更新。Text属性显示正常,仅双向绑定存在问题。
自定义控件XAML代码
<ContentView xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit" x:Class="PaperScoreTracker.Controls.PaperCheckBox" x:Name="this"> <HorizontalStackLayout BindingContext="{x:Reference this}"> <CheckBox x:Name="Part_CheckBox" IsChecked="{Binding IsChecked}"/> <Label FontSize="20" Text="{Binding Text}"/> </HorizontalStackLayout> </ContentView>
自定义控件后台代码
public partial class PaperCheckBox : ContentView { public static readonly BindableProperty IsCheckedProperty = BindableProperty.Create(nameof(IsChecked), typeof(bool), typeof(PaperCheckBox), false); public static readonly BindableProperty TextProperty = BindableProperty.Create(nameof(Text), typeof(string), typeof(PaperCheckBox), string.Empty); public bool IsChecked { get => (bool)GetValue(IsCheckedProperty); set => SetValue(IsCheckedProperty, value); } public string Text { get => (string)GetValue(TextProperty); set => SetValue(TextProperty, value); } public PaperCheckBox() { InitializeComponent(); } }
页面使用代码
<controls:PaperCheckBox Grid.Row="1" Grid.Column="0" IsChecked="{Binding ReverseScoring}" Text="Reverse scoring"/>
解决方法
问题出在两个关键环节:可绑定属性的默认绑定模式、内部CheckBox的绑定模式。
1. 修改IsChecked可绑定属性的绑定模式
MAUI中BindableProperty默认的BindingMode是OneWay,仅支持从VM到控件的单向同步。需要显式设置为TwoWay,让控件属性变化能反向同步到VM:
public static readonly BindableProperty IsCheckedProperty = BindableProperty.Create( nameof(IsChecked), typeof(bool), typeof(PaperCheckBox), false, BindingMode.TwoWay); // 新增双向绑定模式设置
2. 内部CheckBox绑定设置双向模式
内部原生CheckBox的IsChecked绑定需要设置Mode=TwoWay,确保用户操作UI时,值能同步到自定义控件的IsChecked属性:
<CheckBox x:Name="Part_CheckBox" IsChecked="{Binding IsChecked, Mode=TwoWay}"/>
3. 确认VM属性实现可观察性
确保VM中的ReverseScoring属性实现了INotifyPropertyChanged接口,比如使用MAUI CommunityToolkit的[ObservableProperty]特性:
using CommunityToolkit.Mvvm.ComponentModel; public partial class YourViewModel : ObservableObject { [ObservableProperty] private bool reverseScoring; }
或者手动实现:
public class YourViewModel : INotifyPropertyChanged { private bool _reverseScoring; public bool ReverseScoring { get => _reverseScoring; set { if (_reverseScoring != value) { _reverseScoring = value; OnPropertyChanged(nameof(ReverseScoring)); } } } public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } }
完成以上修改后,勾选自定义CheckBox时,VM的ReverseScoring属性就能正常同步更新了。
内容的提问来源于stack exchange,提问作者Adrian Cigher
相关产品推荐
相关产品推荐

