程序整体效果。
1、在Demo项目下创建Models和Services文件夹。如下图。
2、在 Models文件夹中创建ToDoItem.cs,在Services文件夹中创建ToDoListService.cs代码如下。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Demo.Models
{
public class ToDoItem
{
public string Description { get; set; }=String.Empty;
public bool IsChecked { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Demo.Models;
namespace Demo.Services
{
public class ToDoListService
{
public IEnumerable<ToDoItem> GetItems() => new[]
{
new ToDoItem { Description = "Walk the dog" },
new ToDoItem { Description = "Buy some milk" },
new ToDoItem { Description = "Learn Avalonia", IsChecked = true },
};
}
}
3、在Demo项目下创建视图模型,ViewModels文件夹中创建ToDoListViewModel.cs。代码如下。
using Demo.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Demo.ViewModels
{
public class ToDoListViewModel : ViewModelBase
{
public ToDoListViewModel(IEnumerable<ToDoItem> items)
{
ListItems = new ObservableCollection<ToDoItem>(items);
}
public ObservableCollection<ToDoItem> ListItems { get; }
}
}
对MainWindowViewModel.cs文件进行修改,代码如下。
using Demo.Services;
namespace Demo.ViewModels;
public class MainViewModel : ViewModelBase
{
public ToDoListViewModel ToDoListViewModel { get; }
public MainViewModel()
{
var service = new ToDoListService();
ToDoListViewModel = new ToDoListViewModel(service.GetItems());
}
}
4、添加数据绑定,修改ToDoListView.axaml文件如下。
<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"
mc:Ignorable="d" d:DesignWidth="250" d:DesignHeight="450"
x:Class="Demo.Views.ToDoListView"
xmlns:vm="using:Demo.ViewModels"
x:DataType="vm:ToDoListViewModel">
<DockPanel>
<Label Content="111"></Label>
<Button DockPanel.Dock="Bottom"
HorizontalAlignment="Stretch"
HorizontalContentAlignment="Center">
Add Item
</Button>
<ItemsControl ItemsSource="{Binding ListItems}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<CheckBox Margin="4"
IsChecked="{Binding IsChecked}"
Content="{Binding Description}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</DockPanel>
</UserControl>
注意代码中的
xmlns:vm="using:Demo.ViewModels"