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

MAUI中如何将第二个ListView的数据源绑定到第一个选中项的集合?

解决MAUI中两个ListView联动显示的问题

问题原因分析

你的代码存在两个核心问题导致第二个ListView无法联动:

  1. 第二个ListView的ItemsSource绑定语法错误,引用UI元素的方式不正确
  2. ViewModel中的选中项属性未实现属性变更通知,导致选中项变化时UI无法感知更新

解决方案

方式一:基于MVVM模式的推荐实现(更规范)

这种方式通过ViewModel的选中项属性来联动,符合MVVM设计原则,避免UI元素之间的直接依赖。

1. 确保ViewModel实现INotifyPropertyChanged接口

ViewModel必须实现该接口才能在属性变化时通知UI更新:

using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;

public class MainViewModel : INotifyPropertyChanged
{
    // 存储应用列表,推荐用ObservableCollection而非List,自动通知集合变化
    public ObservableCollection<Aplicacion> Aplicaciones { get; set; }

    private Aplicacion _aplicacionesSelectedItem;
    // 选中的应用项,变更时触发通知
    public Aplicacion AplicacionesSelectedItem
    {
        get => _aplicacionesSelectedItem;
        set
        {
            if (_aplicacionesSelectedItem != value)
            {
                _aplicacionesSelectedItem = value;
                OnPropertyChanged();
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    // 构造函数初始化测试数据
    public MainViewModel()
    {
        Aplicaciones = new ObservableCollection<Aplicacion>();
        
        // 添加示例数据
        var app1Acciones = new List<Accion>
        {
            new Accion("登录", "执行用户登录操作"),
            new Accion("退出", "执行用户退出操作")
        };
        Aplicaciones.Add(new Aplicacion("用户中心", app1Acciones));

        var app2Acciones = new List<Accion>
        {
            new Accion("查询订单", "查询历史订单列表"),
            new Accion("创建订单", "创建新的购物订单")
        };
        Aplicaciones.Add(new Aplicacion("订单管理", app2Acciones));
    }
}

2. 修改XAML中第二个ListView的绑定

将第二个ListView的ItemsSource绑定到ViewModel的选中项的Acciones集合:

<ListView x:Name="lvAplicaciones" Background="red"
          SeparatorVisibility="Default"
          SeparatorColor="AliceBlue"
          VerticalScrollBarVisibility="Always"
          ItemsSource="{Binding Aplicaciones}"
          SelectedItem="{Binding AplicacionesSelectedItem}"
          HeightRequest="50"
          HorizontalOptions="CenterAndExpand">
    <ListView.ItemTemplate>
        <DataTemplate>
            <TextCell Text="{Binding Nombre}"/>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

<ListView x:Name="lvAcciones" Background="Yellow"
          SeparatorVisibility="Default"
          SeparatorColor="AliceBlue"
          VerticalScrollBarVisibility="Always"
          <!-- 直接绑定ViewModel中的选中项属性 -->
          ItemsSource="{Binding AplicacionesSelectedItem.Acciones}"
          SelectedItem="{Binding AccionesSelectedItem}"
          HeightRequest="50"
          HorizontalOptions="CenterAndExpand">
    <ListView.ItemTemplate>
        <DataTemplate>
            <TextCell Text="{Binding Nombre}"/>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

3. 设置页面的BindingContext

在页面的构造函数中绑定ViewModel:

public MainPage()
{
    InitializeComponent();
    BindingContext = new MainViewModel();
}

方式二:直接修正UI元素引用的绑定(快速修复)

如果不想修改ViewModel,仅修正XAML的绑定语法也能实现联动,但不符合MVVM模式:

<ListView x:Name="lvAcciones" Background="Yellow"
          SeparatorVisibility="Default"
          SeparatorColor="AliceBlue"
          VerticalScrollBarVisibility="Always"
          <!-- 使用{x:Reference}正确引用第一个ListView -->
          ItemsSource="{Binding Source={x:Reference lvAplicaciones}, Path=SelectedItem.Acciones}"
          SelectedItem="{Binding AccionesSelectedItem}"
          HeightRequest="50"
          HorizontalOptions="CenterAndExpand">
    <ListView.ItemTemplate>
        <DataTemplate>
            <TextCell Text="{Binding Nombre}"/>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

额外注意事项

  • 若Acciones集合后续会动态添加/删除元素,建议将Aplicacion中的List<Accion>改为ObservableCollection<Accion>,这样集合变化时UI会自动更新
  • 确保Aplicacion和Accion类的属性是公共可访问的,你的现有代码中属性定义是正确的

内容的提问来源于stack exchange,提问作者Álvaro García

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 18:24:40