









另外,命令绑定只需要在视图模型中增加私有的方法,用[RelayCommand] 标记,则会默认生成对应的 方法名+Command 的ICommand 类型的方法共UI绑定使用
<Window xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="using:AvaMvvmDemo.ViewModels"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:DataType="vm:MainViewModel"
x:Class="AvaMvvmDemo.Views.MainWindow"
Icon="/Assets/avalonia-logo.ico"
Title="AvaMvvmDemo"
Width="800" Height="600"
>
<Grid RowDefinitions="Auto,*" ShowGridLines="True">
<StackPanel Orientation="Horizontal" Height="40">
<TextBlock Text="{Binding Caption}" VerticalAlignment="Center"/>
<Button Content="SayHello" Width="80" Height="35" Command="{Binding SayHelloCommand}" VerticalContentAlignment="Center" VerticalAlignment="Center" Background="AliceBlue" Margin="10 5"/>
<!--绑定到其他控件 用#控件名.属性 来替代WPF中的ElementName-->
<TextBlock VerticalAlignment="Center" Text="{Binding #tb1.Text}" Foreground="Red" Margin="10 0" />
</StackPanel>
<Grid Grid.Row="1" ColumnDefinitions="*,*,*" ShowGridLines="True">
<ListBox x:Name="lb" ItemsSource="{Binding Products}">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid ColumnDefinitions="*,*,*,*">
<TextBlock Text="{Binding Id}" Grid.Column="0"/>
<TextBlock Text="{Binding Name}" Grid.Column="1" />
<TextBlock Text="{Binding Description}" Grid.Column="2" />
<TextBlock Text="{Binding Price}" Grid.Column="3" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Grid>
</Window>
Models
namespace AvaMvvmDemo.Models
{
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
}
}
ViewModels
using AvaMvvmDemo.Models;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System.Collections.ObjectModel;
namespace AvaMvvmDemo.ViewModels
{
public partial class MainViewModel:ObservableObject
{
[ObservableProperty]
private ObservableCollection<Product> _products=new ObservableCollection<Product>();
public MainViewModel()
{
Products.Add(new Product { Id=1,Name="篮球",Description="体育用品",Price=125.0M});
Products.Add(new Product { Id = 2,Name = "足球", Description = "体育用品", Price = 320.0M });
Caption = "Test";
}
[ObservableProperty]
private string _caption;
[RelayCommand]
private void SayHello()
{
Caption = "点击了SayHello";
}
}
}
效果

此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。