Avalonia 中创建一个 TODO List 应用程序的一些要点

Avalonia 中创建一个 TODO List 应用程序的一些要点

项目请参考 https://gitee.com/fanbal/my-avalonia-todolist

一、集合项删除的推荐做法

我认为推荐使用 ICommand 属性并且在创建时赋值会是一种更好的方式。

注意这边 todoListItem.DeleteCommand = new RelayCommand() 的写法。

  protected TodoListItem CreateTodoListItem(string content)
  {
      var todoListItem = new TodoListItem()
      {
          Content = content,
      };
      todoListItem.DeleteCommand = new RelayCommand(() =>
      {
          TodoList.Remove(todoListItem);
          todoListItem.DeleteCommand = null;
      });

      return todoListItem;
  }

二、使用 DesignViewModel 为开发提供便利

为了方便 Avalonia 开发的时候提供一些便利,我们可以创建一个我们目前 ViewModel 的继承、为它提供给一些默认值,比如这样:

public class DesignMainViewModel : MainViewModel
{
    public DesignMainViewModel()
    {
        string[] arr = [
            "111",
            "2222",
            "333333",
            "444444",
            "55555555",
            ];

        foreach (var item in arr)
        {
            TodoList.Add(CreateTodoListItem(item));
        }


    }
}

三、Style 是交互的精髓

如果我们要实现一些交互,比如鼠标悬停实现当前格子某个按钮的显示,那么,使用 Style 来完全对应 WPF 中 Trigger 的功能是必不可少的。

我们下面写的样式,就会对一个承载了 Button 的 Grid 生效。

<Style Selector="Grid.trigger">
    <Setter Property="Background" Value="Transparent" />
</Style>
<Style Selector="Grid.trigger  Button">
    <Setter Property="IsVisible" Value="False" />
</Style>
<Style Selector="Grid.trigger:pointerover Button">
    <Setter Property="IsVisible" Value="True" />
</Style>

四、MVVM 不是万能的,控件的事件订阅同样很重要

有一些交互上的需求是绑定无法解决的,这个时候,就不得不去写事件了。
就像在项目中的键盘事件,使用 Command 就没有办法很好的解决这样的问题。

posted @ 2025-03-30 13:17  fanbal  阅读(136)  评论(0)    收藏  举报