I have googled around but with very limited luck. I have a question regarding editable WPF DataGrid; in a CellEditingTemplate a ComboBox is shown, but in CellTemplate a TextBox with corresponding ComboBox value is shown. My code looks something like this:
<DataGridTemplateColumn Header="Unit">
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<ComboBox Name="comboBoxUnit" ItemsSource="{Binding ...}" SelectedValue="{Binding UnitId, ValidatesOnDataErrors=True}" SelectedValuePath="Id">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Id}" />
<TextBlock Text=" " />
<TextBlock Text="{Binding Name}" />
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="<would like to have selected Unit's Id and Name here>" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
How can I achieve this? Separate property in a class (to have UnitId and UnitName properties) is not a problem, I can add it, but how to bind both to ComboBox then? Can I access CellEditingTemplate ComboBox in CellTemplate? It seems like they are in "different namespaces" since I can name controls in both with same names...
Any ideas, pointers? Thanks in advance, DB
The easiest way to achieve the same thing is to use a
DataGridComboBoxColumn.However, in my current project we had so many problems with the
DataGridComboBoxColumnthat we don't use it anymore. Instead we use aDataGridTemplateColumnwith aComboBoxin theCellEditingTemplateand aTextBlockin theCellTemplate(just like you're doing).To be able to display data based on an Id (to get the same functionality in the
TextBlockas in theComboBox) we use a converter calledCodeToDescriptionConverter. It's usable like thisBindingis the value we look for (Id)Bindingis theIListwe look inCodeAttributeis the name of the property we want to compare to the id (firstBinding)DescriptionAttributesare the properties we want to return formatted asStringFormatAnd in your case: Find the instance in
Unitswhere the propertyIdhas the same value asUnitIdand for this instance return the values ofIdandNameformatted as{0} - {1}CodeToDescriptionConverteruses reflection to achieve thisI uploaded a sample application here: CodeToDescriptionSample.zip.
It includeds a
DataGridTemplateColumnwithCodeToDescriptionConverterand aDataGridComboBoxColumnthat does the same thing. Hope this helps