You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Maui:代码实现ContentView与父ViewModel的MVVM绑定问题

问题解决:.NET Maui中RadListView模板里ContentView绑定失效

问题核心

在.NET Maui项目中使用RadListView的ItemTemplateSelector时,通过代码创建的带BindableProperty的ContentView无法正确绑定到ViewModel的属性。尝试过RelativeBindingSource但无效,不清楚代码层面如何实现类似XAML中BindingContext={x:Reference this}的效果。

解决方案

1. 修复ContentView的BindableProperty实现

你的MultipleOptionView中,CLR属性OptionsNumber没有正确关联到定义的BindableProperty,导致绑定无法传递值。必须通过GetValue和SetValue来关联:

public class MultipleOptionView : ContentView
{
    public static readonly BindableProperty OptionsNumberProperty = 
        BindableProperty.Create(
            nameof(OptionsNumber), 
            typeof(int), 
            typeof(MultipleOptionView), 
            9,
            propertyChanged: OnOptionsNumberChanged);

    public MultipleOptionView()
    {
    }

    public int OptionsNumber
    {
        get => (int)GetValue(OptionsNumberProperty);
        set => SetValue(OptionsNumberProperty, value);
    }

    private static void OnOptionsNumberChanged(BindableObject bindable, object oldValue, object newValue)
    {
        var view = bindable as MultipleOptionView;
        if (view != null && newValue is int number && number != 0)
        {
            view.CreateView();
        }
    }

    void CreateView()
    {
        // 你的视图创建逻辑
    }
}

2. 确认DataTemplate中的绑定上下文

在RadListView的ItemTemplate中,每个项的BindingContext是单个Question对象,你当前的绑定代码逻辑正确:

var bindingOptionsNumber2 = new Binding(nameof(Question.QuestionOptionNumber), BindingMode.TwoWay);
var multipleOptionView = new MultipleOptionView();
multipleOptionView.SetBinding(MultipleOptionView.OptionsNumberProperty, bindingOptionsNumber2);

注意:需确保Question类实现INotifyPropertyChanged接口,否则属性变更无法通知到绑定。

3. 若需绑定到父ViewModel(而非Item对象)

如果需求是绑定到QuestionsViewModel(而非单个Question)的属性,可通过RelativeBindingSource在代码中指定:

var binding = new Binding(
    nameof(QuestionsViewModel.YourParentProperty),
    BindingMode.TwoWay,
    source: new RelativeBindingSource(
        RelativeBindingSourceMode.FindAncestor,
        typeof(QuestionsViewModel)
    )
);
multipleOptionView.SetBinding(MultipleOptionView.OptionsNumberProperty, binding);

验证要点

  • 确认Question.QuestionOptionNumber有正确初始值,且实现INotifyPropertyChanged
  • 修复后的MultipleOptionView中,CLR属性必须通过GetValue/SetValue关联BindableProperty
  • RadListView的ItemsSource已正确设置为vm.Questions

内容的提问来源于stack exchange,提问作者vordonez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 18:53:10