I am having a combo box in data grid in WPF. I am unable to bind data. I have used the below code.
XAML
<DataGrid
Name="grdDetails"
Width="578"
Height="149"
ScrollViewer.VerticalScrollBarVisibility="Visible"
ScrollViewer.HorizontalScrollBarVisibility="Visible"
AutoGenerateColumns="False"
MouseRightButtonUp="grdDetails_MouseRightButtonUp"
SelectionChanged="grdDetails_SelectionChanged">
<DataGrid.Columns>
<DataGridTemplateColumn Width="80" Header="Country">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Country}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<ComboBox
Name="cbCountry"
ItemsSource="{Binding Path=CountryList}"
SelectedItem="Code"
DisplayMemberPath="Code"
SelectedValuePath="Code"/>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
Code Behind (C#)
List<CountryDTO> CountryList = new List<CountryDTO>();
CountryList = refController.GetCountryData(); // this brings the list of Country.
Please advice.
Using MVVM you need to create a view model class which would look like below and in your code behind assign an instance of it to the DataContext property of the Window.
Then the binding would like this:
ItemsSource="{Binding Path=CountryList , RelativeSource={RelativeSource FindAncestor, AncestorType=Window}}"
The view model class would look like this:
public class MyViewModel
{
public ObservableCollection<CountryDTO> CountryList { get; private set; }
public MyViewModel(SomeControler refController)
{
CountryList = new ObservableCollection(refController.GetCountryData());
}
}