1

i'm new to WPF and i just learned today data binding, so i may have some basics errors.

Goal : I want a column in the data grid that will function like a combo box column that shows all the items from a string list.

XAML :

<DataGrid  x:Name="dataGrid" AutoGenerateColumns="False">
   <DataGrid.Columns>
      <DataGridComboBoxColumn   Header="CitiesColumn" ItemsSource="{Binding Cities}/">
   </DataGrid.Columns>
</DataGrid>

Code-Behind :

ObjectModel type :

class CitiesModel 
{
    private List<string> _Cities;
    public List<string> Cities { get { return _Cities; } set { _Cities = value ; } }
    public CitiesModel()
    {
        Cities = new List<string>
        {
            "Berlin",
            "Rome",
            "Paris",
            "Barcelona"
        }; 
    }
}

window.cs file :

public partial class MainWindow : Window
{
    CitiesModel Cm;
    public MainWindow()
    {
        Cm = new CitiesModel();
        DataContext = Cm;
        InitializeComponent();
    }
}

It shows no data at all not even a cell in the grid.. and when i tried the same code on a regular combo box it showed all of the data

XAML :

<ComboBox  ItemsSource="{Binding Cities}"/>

I searched online and saw a way to do it with a DataGridTemplateColumn instead of a ComboBox Column, and in this way i cant even see the column header.

XAML:

<DataGrid Margin="44,65,52,-24" AutoGenerateColumns="False">
    <DataGridTemplateColumn Header="Street Address">
        <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
                <ComboBox ItemsSource="{Binding Cities}"/>
            </DataTemplate>
        </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>

thanks.

zzzz
  • 161
  • 1
  • 9

1 Answers1

0
  1. Bind the ItemsSource of the DataGrid, otherwise there won't even be any items.
  2. The bindings in the data grid columns have a different DataContext than the grid itself, namely the context is the current row. So if you want to bind to another context you have to explicitly change the binding source.
H.B.
  • 166,899
  • 29
  • 327
  • 400
  • thanks for the answer , i binded the ItemsSource of the data grid , and now i can see some cells, be still they are not binded to the Cities property , can you maybe show me a small example of how to implement the 2 point you wrote? – zzzz Jul 11 '16 at 19:24
  • No. Read the binding documentation/overview on MSDN or search stackoverflow, there are examples of just about anything here. – H.B. Jul 11 '16 at 19:29