ReactivePropertyをインストール
Visual Studio 2022のメニュー→「プロジェクト」→「NuGetパッケージの管理」
ReactivePropertyを検索しインストール
System.Reactiveを検索しインストール
ソースコード
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="CollectionViewWithReactiveCollection.MainPage">
<VerticalStackLayout>
<CollectionView
ItemsSource="{Binding Items}"
SelectedItem="{Binding SelectedItem.Value}"
SelectionMode="Single">
<CollectionView.ItemTemplate>
<DataTemplate>
<Grid Padding="10">
<Grid.RowDefinitions>
<RowDefinition Height="40" />
<RowDefinition Height="40" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="80" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Label Grid.Column="0"
Text="{Binding SEQ}"
FontSize="18" />
<Label Grid.Column="1"
Text="{Binding Name}"
FontSize="18" />
</Grid>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
<Label
Text="{Binding SelectedName.Value}"
FontSize="18"/>
</VerticalStackLayout>
</ContentPage>
ファイル名:MainPage.xaml.cs
namespace CollectionViewWithReactiveCollection;
public partial class MainPage : ContentPage
{
ViewModel _vm;
public MainPage()
{
InitializeComponent();
this.Loaded += MainPage_Loaded;
}
private void MainPage_Loaded(object sender, EventArgs e)
{
_vm = new ViewModel();
this.BindingContext = _vm;
}
}
ファイル名:ViewModel.cs
using Reactive.Bindings;
namespace CollectionViewWithReactiveCollection;
public class ViewModel
{
public ReactiveCollection<Card> Items { get; set; } = new ReactiveCollection<Card>();
public ReactiveProperty<Card> SelectedItem { get; } = new ReactiveProperty<Card>();
public ReactiveProperty<string> SelectedName { get; } = new ReactiveProperty<string>("");
public ViewModel()
{
SelectedItem.Subscribe((o) => {
SelectedName.Value = o?.Name;
});
int i = 0;
Items.Add(new Card { SEQ = i++, Name = "TARO" });
Items.Add(new Card { SEQ = i++, Name = "HANA" });
Items.Add(new Card { SEQ = i++, Name = "KENJIRO" });
Items.Add(new Card { SEQ = i++, Name = "MINA" });
Items.Add(new Card { SEQ = i++, Name = "HIRAKU" });
}
}
ファイル名:Card.cs
namespace CollectionViewWithReactiveCollection;
public class Card
{
public long SEQ { get; set; } = -1;
public string Name { get; set; } = "";
}
コメント