2
votes

I have a DataTemplate for a ComboBox in a GridView column. I want to display a ComboBox when the cell is being edited and a TextBlock otherwise. However I am having trouble getting the TextBox to display the desired value.

The ViewModel for the row has only RegionId but the Combo is bound to a collection of Region objects (with Id and Name). I'd like to display the Region.Name when the value is not being edited, at the moment I can only find a way to show the RegionId because the ViewModel does not contain a Name property.

I am using a Telerik combobox but I think my problem would be the same with a standard ComboBox control as I think this is just a binding issue.

How should I bind my TextBlock in the DataTemplate?

<telerik:GridViewDataColumn>
<telerik:GridViewDataColumn.CellTemplate>
    <DataTemplate>
        <TextBlock Text="{Binding RegionId}" />  <!-- would like Region.Name -->
    </DataTemplate>
</telerik:GridViewDataColumn.CellTemplate>
<telerik:GridViewDataColumn.CellEditTemplate>
    <DataTemplate>
        <telerik:RadComboBox ItemsSource="{Binding Source={StaticResource regionView}}" 
            DisplayMemberPath="Name" SelectedValuePath="Id" SelectedValue="{Binding Path=RegionId, Mode=TwoWay}" />
    </DataTemplate>
</telerik:GridViewDataColumn.CellEditTemplate>
</telerik:GridViewDataColumn>
1
Why can't you add the Name property to your ViewModel? - Adolfo Perez
Good point, I'd like to but it's specified in a data contract that is fixed. - openshac
Why don't you put Region.Name? - Phil
Because it has to be bound to the ViewModel for that row, and the ViewModel has only RegionId - openshac
You could use a converter to solve this Problem. Bind to RegionId, use your regionView as ConverterParameter and search through it in your converter. - Florian Gl

1 Answers

0
votes

ViewModels are supposed to be reflected in the View, so your best course of action would just be to add a Name property to your ViewModel

But since you said in a comment that your ViewModel is defined in a fixed data contract, you could instead use a Converter to convert the Id to the Name

If your converter code has access to the list of Regions, then it's easiest to do with an IValueConverter

<TextBlock Text="{Binding RegionId, Converter={StaticResource MyRegionIdToNameConverter}}" />

But if not, you'll have to use an IMultiValueConverter to pass both parameters in

<TextBlock.Text>
    <MultiBinding Converter="{StaticResource MyRegionIdToNameMultiConverter}">
        <Binding Source="{StaticResource regionView}"/>
        <Binding Path="RegionId" />
    </MultiBinding>
</TextBlock.Text>