Quantcast
Channel: C#タグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 9529

[WPF/xaml] ListViewのGrid表示を使う

$
0
0
やりたいこと ListViewに、自分で作ったデータ用クラスのメンバを表示させたい。下記のようなイメージ。 やりかた <ListView>と<GridView>を使う。 MainWindow.xaml <Window x:Class="WpfApp48.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 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" xmlns:local="clr-namespace:WpfApp48" mc:Ignorable="d" Title="MainWindow" Height="300" Width="200"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="10*"/> <RowDefinition Height="1*"/> </Grid.RowDefinitions> <ListView ItemsSource="{Binding DataList}"> <ListView.View> <GridView> <GridViewColumn Header="機体" DisplayMemberBinding="{Binding MachineName}" Width="80" /> <GridViewColumn Header="パイロット" DisplayMemberBinding="{Binding PilotName}" Width="80" /> </GridView> </ListView.View> </ListView> <Button Grid.Row="1" Content="ボタン" Click="Button_Click"/> </Grid> </Window> MainWindow.xaml.cs using System; using System.Collections.ObjectModel; using System.ComponentModel; using System.Windows; namespace WpfApp48 { public partial class MainWindow : Window, INotifyPropertyChanged { #region INotifyPropertyChanged public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string propertyName)=> this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); #endregion // ガンダム情報を格納 public ObservableCollection<MyData> DataList { get; set; } = new ObservableCollection<MyData>(); public MainWindow() { InitializeComponent(); this.DataContext = this; } // ボタンをおしたらデータの中身を追加 private void Button_Click(object sender, RoutedEventArgs e) { DataList.Add(new MyData() { MachineName = "ガンダム", PilotName = "アムロ" }); DataList.Add(new MyData() { MachineName = "シャアザク", PilotName = "シャア" }); DataList.Add(new MyData() { MachineName = "グフ", PilotName = "誰やったっけ?" }); DataList.Add(new MyData() { MachineName = "Zガンダム", PilotName = "カミーユ" }); DataList.Add(new MyData() { MachineName = "ジ・オ", PilotName = "シロッコ" }); DataList.Add(new MyData() { MachineName = "百式", PilotName = "シャア" }); DataList.Add(new MyData() { MachineName = "ZZガンダム", PilotName = "ジュドー" }); } } /// <summary> /// ガンダム情報クラス /// </summary> public class MyData { public string MachineName { get; set; } public string PilotName { get; set; } } } <GridViewColumn>のHeaderに、列のタイトルを書き、DisplayMemberBindingに、列に表示したいデータクラスのメンバの名前を書く。 参考 ListView(MsDocs) ListViewのカスタムの仕方が書いてある ListViewのグループ ツリービューでもいいかも?

Viewing all articles
Browse latest Browse all 9529

Trending Articles