自定义BindableProperty绑定失效问题排查
自定义ContentView绑定值不更新的问题与解决方法
在为自定义ContentView绑定值时遇到问题:ContentPage中使用了作为ContentView的AccountStatusView,它包含AccountStatusDto类型的BindableProperty,但绑定后该属性从未更新。以下是相关代码:
MainPage - XAML
<Grid> <controls:AccountStatusView AccountStatus="{Binding AccountStatus}" /> </Grid>
MainPage - C#
public partial class MainPage : ContentPage { public MainPage(ViewModel vm) { BindingContext = vm; InitializeComponent(); } }
ViewModel
public partial class ViewModel : ObservableObject { [ObservableProperty] private AccountStatusDto _accountStatus; // . . . public async Task InitializeAsync() { AccountStatus = await _repo.GetAccountStatus(); } }
AccountStatusView - C#
public partial class AccountStatusView : ContentView { public static readonly BindableProperty AccountStatusProperty = BindableProperty.Create(nameof(AccountStatus), typeof(AccountStatusDto), typeof(AccountStatusView), propertyChanged: DoSomething); public static void DoSomething(BindableObject bindable, object oldvalue, object newvalue) { // do something with the new value } public AccountStatusDto AccountStatus { get => (AccountStatusDto)GetValue(AccountStatusProperty); set => SetValue(AccountStatusProperty, value); } }
解决方案
找到的有效解决方法如下:
创建包含XAML的自定义组件时,请勿设置
BindingContext = this;
另外,通过x:Name访问组件属性的方案也能解决问题:
为自定义组件设置
x:Name,并将其作为绑定的Source:<VerticalStackLayout ... x:Name="me" <!-- 重要!可按需修改名称。 --> x:Class="DataBindingExample.Card"> ... <Label Text="{Binding CardIncrement, Source={x:Reference me}}" ...
该方案完美解决了问题。
内容的提问来源于stack exchange,提问作者Andres
相关产品推荐
相关产品推荐

