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
DataGridComboBoxColumn
that we don't use it anymore. Instead we use aDataGridTemplateColumn
with aComboBox
in theCellEditingTemplate
and aTextBlock
in theCellTemplate
(just like you're doing).To be able to display data based on an Id (to get the same functionality in the
TextBlock
as in theComboBox
) we use a converter calledCodeToDescriptionConverter
. It's usable like thisBinding
is the value we look for (Id)Binding
is theIList
we look inCodeAttribute
is the name of the property we want to compare to the id (firstBinding
)DescriptionAttributes
are the properties we want to return formatted asStringFormat
And in your case: Find the instance in
Units
where the propertyId
has the same value asUnitId
and for this instance return the values ofId
andName
formatted as{0} - {1}
CodeToDescriptionConverter
uses reflection to achieve thisI uploaded a sample application here: CodeToDescriptionSample.zip.
It includeds a
DataGridTemplateColumn
withCodeToDescriptionConverter
and aDataGridComboBoxColumn
that does the same thing. Hope this helps