Avalonia 如何在 ItemsPanel 中绑定 MainViewModel 中的 Command?

本文介绍了如何在AvaloniaUI框架中使用ItemsPanel时处理列表项的删除操作,重点讲解了如何解决由于数据上下文问题导致的DeleteCommand找不到的问题,提供了三种解决方案:编译绑定禁用、反射绑定和显式类型转换。
摘要由CSDN通过智能技术生成

当需要在 Avalonia 中展示一个列表时,ItemsPanel 是一个不错的选择。如果需要针对列表中的某一项进行操作,通常不会在 ItemModel 中进行实现,而是放入列表所在的 ViewModel 中:

public class ItemModel
{
    public ItemModel(string name)
    {
        this.Name = name;
    }
    public string Name { get; }
}
using CommunityToolkit.Mvvm.Input;
using System.Collections.ObjectModel;


public partial class MainViewModel : ViewModelBase
{
    public ObservableCollection<ItemModel> Items { get; } = new ObservableCollection<ItemModel>();


    public MainViewModel()
    {
        for (int i = 0; i < 50; i++)
        {
            this.Items.Add(new ItemModel("Item " + (i + 1)));
        }
    }


    [RelayCommand]
    private void Delete(ItemModel item)
    {
        this.Items.Remove(item);
    }
}

后端代码并不复杂,但下面的界面代码会导致编译失败:

<UserControl xmlns="https://github.com/avaloniaui"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:vm="clr-namespace:ItemsPanelMainCommand.ViewModels"
             mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
             x:Class="ItemsPanelMainCommand.Views.MainView"
             x:DataType="vm:MainViewModel">
  <Design.DataContext>
    <vm:MainViewModel />
  </Design.DataContext>
  <ItemsControl ItemsSource="{Binding Items}">
    <ItemsControl.ItemTemplate>
      <DataTemplate>
        <StackPanel Orientation="Horizontal">
          <TextBlock Text="{Binding Name}"></TextBlock>
          <Button Command="{Binding DeleteCommand}" CommandParameter="{Binding}">删除</Button>
        </StackPanel>
      </DataTemplate>
    </ItemsControl.ItemTemplate>
  </ItemsControl>
</UserControl>

报错信息如下:

Unable to resolve property or method of name 'DeleteCommand' on type 'ItemsPanelMainCommand.ViewModels.ItemModel'.

AVLN:0004

这是因为进入 ItemsControl 后,控件的 DataContext 被设置为了 ItemModel 的实例,而 ItemModel 本身是不存在 DeleteCommand 的,要想办法找到外层的 MainViewModel 才行。

解决方法

<Button Command="{Binding $parent[ItemsControl].DataContext.DeleteCommand}" x:CompileBindings="False" CommandParameter="{Binding}">删除-方案1</Button>
<Button Command="{ReflectionBinding $parent[ItemsControl].DataContext.DeleteCommand}" CommandParameter="{Binding}">删除-方案2</Button>
<Button Command="{Binding $parent[ItemsControl].((vm:MainViewModel)DataContext).DeleteCommand }" CommandParameter="{Binding}">删除-方案3</Button>

上面提供了三种方案大同小异:都是通过找到父级的数据上下文然后调用父级控件上下文的 DeleteCommand 。主要区别是:在处理编译绑定时使用了不同的策略。

  • 方案 1 为控件附加了一个 x:CompileBindings 属性,并设置值为 False,以此来抑制编译绑定的检查从而保证编译成功。

  • 方案 2 直接使用了 ReflectionBinding ,即“反射绑定”。这种绑定方式也不进行编译检查。

  • 方案 3 在拿到父级的 DataContext 之后进行了显示的类型转换,确保类型正确后编译通过。

总结

本文所述的代码虽然简单,但也是新手入门期间大概率会碰上的问题。作为一名开发人员,我更倾向于使用第三种方式。本文所示代码已经上传,可以在以下地址查看:

https://gitee.com/coderbusy/demo/tree/master/avaloina/ItemsPanelMainCommand

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值