Reputation: 5
I have a datagrid which is bound to my ObservableCollection. Each column is bound to property of the class wellenelement. Now i would like to convert the column "Art" to a combobox column, where the user can choose from 3 different options. How can i create these 3 Combobox items and add it to the datagrid?
<DataGrid AutoGenerateColumns="True" Name="dataGrid1" ItemsSource="{Binding}" >
</DataGrid>
```xaml
```c#
public partial class MainWindow : Window
{
public ObservableCollection<Wellenelement> Welle1;
public MainWindow()
{
InitializeComponent();
Welle1 = new ObservableCollection<Wellenelement>();
dataGrid1.DataContext = Welle1;
}
}
```c#
```c#
public class Wellenelement
{
public string Art { get; set; }
public string UK { get; set; }
public string DA { get; set; }
public string DI { get; set; }
}
```c#
Upvotes: 0
Views: 303
Reputation: 385
If it's the same for each item you can add a collection to the viewmodel and add it as a resource to your view. Then you can set the resource as the itemssource for the DataGridComboBoxColumn.
ViewModel:
public class MainViewModel
{
public MainViewModel()
{
Wellenelements = new ObservableCollection<Wellenelement>()
{
new Wellenelement()
{
UK = "uk1",
DA = "da1",
DI = "di1"
},
new Wellenelement()
{
UK = "uk2",
DA = "da2",
DI = "di2"
},
};
ArtTypes = new List<string>()
{
"new art","old art", "good art","bad art"
};
}
public ObservableCollection<Wellenelement> Wellenelements { get; set; }
public List<string> ArtTypes { get; set; }
}
View:
<Window ...
xmlns:viewmodels="clr-namespace:WpfApp.Viewmodels"
...>
<Window.DataContext>
<viewmodels:MainViewModel/>
</Window.DataContext>
<Window.Resources>
<CollectionViewSource x:Key="myCollection" Source="{Binding ArtTypes}"/>
</Window.Resources>
<Grid>
<DataGrid AutoGenerateColumns="False"
CanUserAddRows="False"
ItemsSource="{Binding Wellenelements}" >
<DataGrid.Columns>
<DataGridComboBoxColumn ItemsSource="{Binding Source={StaticResource myCollection}}"
SelectedItemBinding="{Binding Art, UpdateSourceTrigger=PropertyChanged}"
Header="Art Combo column"/>
<DataGridTextColumn Binding="{Binding Art}"
IsReadOnly="True"
Header="Selected Art Type"/>
<DataGridTextColumn Binding="{Binding UK}"
Header="UK"/>
<DataGridTextColumn Binding="{Binding DA}"
Header="DA"/>
<DataGridTextColumn Binding="{Binding DI}"
Header="DI"/>
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
Wellenelement class:
public class Wellenelement : ObservableObject
{
public string UK { get; set; }
public string DA { get; set; }
public string DI { get; set; }
private string _art;
public string Art
{
get { return _art; }
set
{
_art = value;
OnPropertyChanged(nameof(Art));
}
}
}
Upvotes: 1