dynamic
にバインドされたリストを使用してListBox
、表示する必要のあるものに基づいてそのリストにデータを入力できます。また、を使用DisplayMemberPath
して、Name
またはその他の一般的なプロパティを表示できます。ListBox
実例:
コード:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private ObservableCollection<dynamic> _listBoxItems = new ObservableCollection<dynamic>();
public ObservableCollection<dynamic> ListBoxItems
{
get { return _listBoxItems; }
set { _listBoxItems = value; }
}
public List<River> Rivers
{
get
{
return new List<River>
{
new River { Name = "River1" } ,
new River { Name = "River2"}
};
}
}
public List<City> Cities
{
get
{
return new List<City>
{
new City { Name = "City1" } ,
new City { Name = "City2"}
};
}
}
private void button_City_Click(object sender, RoutedEventArgs e)
{
ListBoxItems.Clear();
Cities.ForEach(i => ListBoxItems.Add(i));
}
private void button_River_Click(object sender, RoutedEventArgs e)
{
ListBoxItems.Clear();
Rivers.ForEach(i => ListBoxItems.Add(i));
}
}
public sealed class City
{
public string Name { get; set; }
}
public sealed class River
{
public string Name { get; set; }
}
Xaml:
<Window x:Class="WpfApplication10.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="199" Width="191" Name="UI">
<Grid DataContext="{Binding ElementName=UI}" >
<ListBox ItemsSource="{Binding ListBoxItems}" DisplayMemberPath="Name" Margin="0,0,0,29" />
<Button Content="City" Height="23" HorizontalAlignment="Left" Name="button1" VerticalAlignment="Bottom" Width="75" Click="button_City_Click"/>
<Button Content="River" Height="23" HorizontalAlignment="Right" Name="button2" VerticalAlignment="Bottom" Width="75" Click="button_River_Click"/>
</Grid>
</Window>
結果: