Developer technologies | Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
How to bind Combobox to some cells of DataGrid in WPF using MVVM pattern
I will show you a demo of binding ComboBox to DataGrid Cell.
Part1: Code for Model part
public enum SexOpt { Male, Female };
public class Member
{
public string Name { get; set; }
public SexOpt Sex { get; set; }
}
Part2: Code for ViewModel part
public class ViewModel
{
public ObservableCollection<Member> memberData { get; set; }
public ViewModel()
{
memberData = new ObservableCollection<Member>();
Random radom = new Random();
for (int i = 1; i < 10; i++)
{
Member men = new Member();
men.Name = "JOE" + i.ToString();
if (i % 2 == 0)
{
men.Sex = SexOpt.Male;
}
else
{
men.Sex = SexOpt.Female;
}
memberData.Add(men);
}
}
}
Part3: Code for View part, add xmlns:assembly="clr-namespace:System;assembly=mscorlib" for xaml
<Window.Resources>
<ObjectDataProvider x:Key="sexEnum" MethodName="GetValues" ObjectType="{x:Type assembly:Enum}">
<ObjectDataProvider.MethodParameters>
<x:Type Type="local:SexOpt"/>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</Window.Resources>
<Window.DataContext>
<local:ViewModel></local:ViewModel>
</Window.DataContext>
<Grid>
<DataGrid x:Name="dataGrid" ItemsSource="{Binding memberData}" AutoGenerateColumns="False" SelectionMode="Extended" SelectionUnit="CellOrRowHeader" >
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Width="80" Binding="{Binding Name}"/>
<DataGridComboBoxColumn Width="80" Header="Sex"
SelectedItemBinding="{Binding Sex}"
ItemsSource="{Binding Source={StaticResource sexEnum}}"/>
</DataGrid.Columns>
</DataGrid>
</Grid>
The result picture is:
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.