[C# WPF] ListBoxからLIstBoxItemを取得する
ListBoxからListBoxItemを取る方法を聞かれて、サンプルを作ったのでそのまま公開します。
調べたときの検索ワードが悪かったのか、すぐに見つからなかったので。。。
まずListBox
以下のようなボタンが3つ並んでいるListBoxがあるとします。
先頭のボタンだけ選択状態にしてあります。
<Window x:Class="Sample_ListBox.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:Sample_ListBox"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ListBox x:Name="xListBox">
<ListBoxItem IsSelected="True">
<Button x:Name="xButton1" Width="200" Height="40">あした</Button>
</ListBoxItem>
<ListBoxItem>
<Button x:Name="xButton2" Width="200" Height="40">あさって</Button>
</ListBoxItem>
<ListBoxItem>
<Button x:Name="xButton3" Width="200" Height="40">しあさって</Button>
</ListBoxItem>
</ListBox>
</Grid>
</Window>
そしてListBoxItemの取得
コード側ではこのようにして取得できます。
using System.Windows;
using System.Windows.Controls;
namespace Sample_ListBox
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
// インデックス参照でListBoxItemを取得する場合
ListBoxItem itemFromIndex = xListBox.Items.GetItemAt(0) as ListBoxItem;
// 選択されているListBoxItemを取得する場合
ListBoxItem itemFromSelection = xListBox.SelectedItem as ListBoxItem;
}
}
}
おしまい。



ディスカッション
コメント一覧
まだ、コメントがありません