安装Avalonia.Xaml.Behaviors
Install-Package Avalonia.Xaml.Behaviors
DataGridSelectedItemsBehavior.cs
using Avalonia;
using Avalonia.Controls;
using Avalonia.Threading;
using Avalonia.Xaml.Interactivity;
namespace CgdataBase;
public class DataGridSelectedItemsBehavior : Behavior<DataGrid>
{
public static readonly DirectProperty<DataGridSelectedItemsBehavior, IList> SelectedItemsProperty =
AvaloniaProperty.RegisterDirect<DataGridSelectedItemsBehavior, IList>(nameof(SelectedItems),
o => o.SelectedItems, (o, v) => o.SelectedItems = v);
private IList _selectedItems;
public IList SelectedItems
{
get => _selectedItems;
set => SetAndRaise<IList>(SelectedItemsProperty, ref _selectedItems, value as IList);
}
protected override void OnAttached()
{
base.OnAttached();
if (AssociatedObject is { })
{
AssociatedObject.SelectionChanged += AssociatedObject_SelectionChanged;
}
}
protected override void OnDetaching()
{
base.OnDetaching();
if (AssociatedObject is { })
{
AssociatedObject.SelectionChanged -= AssociatedObject_SelectionChanged;
}
}
private void AssociatedObject_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Dispatcher.UIThread.Post(() =>
{
SelectedItems = AssociatedObject.SelectedItems;
});
}
}
前台代码
增加引用
xmlns:i="using:Avalonia.Xaml.Interactivity"
绑定:
<DataGrid
IsReadOnly="True"
ItemsSource="{Binding Items}"
SelectedItem="{Binding SelectedItem}">
<i:Interaction.Behaviors>
<cg2:DataGridSelectedItemsBehavior SelectedItems="{Binding SelectedItems, Mode=TwoWay}" />
</i:Interaction.Behaviors>
</DataGrid>
后台代码
[Reactive] public IList SelectedItems { get; set; }
使用:
var items = SelectedItems.Cast<SatelliteInfo>().ToArray();
标签:MVVM,Xaml,AssociatedObject,SelectedItems,SelectionChanged,DataGrid,using,Avaloni
From: https://www.cnblogs.com/wzwyc/p/18223064