LoginSignup
2
2

More than 5 years have passed since last update.

WPF DataGridComboBoxColumnのItemsSourceにコレクションをバインドする方法

Posted at

たぶんよろしくはない。
改善策があれば教えていただきたいです。
(enumerationであえてバインドしていません)

Person.cs
    class Person
    {
        public string ID { get; set; }
        public string Name { get; set; }
        public string BirthPlace { get; set; }
    }
MainWindow.xaml.cs
    public partial class MainWindow : Window
    {
        private List<string> birthPlaces;
        public MainWindow()
        {
            InitializeComponent();

            birthPlaces = new List<string>
            {
                "Tokyo",
                "Osaka",
                "Aichi"
            };

            ObservableCollection<Person> persons = new ObservableCollection<Person>
            {
                new Person { Name="Aoki", ID="0", BirthPlace="Tokyo"},
                new Person { Name="Aikawa", ID="1", BirthPlace="Osaka" },
                new Person { Name="Adachi", ID="2", BirthPlace="Aichi" }
            };
            dgcbc.ItemsSource = birthPlaces;
            DataContext = persons;
        }
    }
MainWindow.xaml
<Window x:Class="DataGridComboBoxColumnBindingSample.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:DataGridComboBoxColumnBindingSample"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <DataGrid ItemsSource="{Binding}" AutoGenerateColumns="False">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
                <DataGridComboBoxColumn x:Name="dgcbc" SelectedItemBinding="{Binding BirthPlace}"/>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2