I have a DataTemplate with a Combobox inside a ListView like this
<GridViewColumn.CellTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding DataContext.Dimensions, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListView}}}"
DisplayMemberPath="Description"
SelectedValuePath="Id"
SelectedItem="{Binding DimName}"/>
</DataTemplate>
The combobox is populated correctly, but it doesn’t select the content according to underlying field (ie. Dimension.DimName).
Here’s how the ListView is declared
<ListView
Name="lstCriteria"
ScrollViewer.VerticalScrollBarVisibility="Auto"
Margin="5"
AlternationCount="2"
ItemContainerStyle="{StaticResource CriteriaItemStyle}"
ItemsSource="{Binding Source={StaticResource CriteriaList}}" DockPanel.Dock="Top"
IsSynchronizedWithCurrentItem="True">
If I replace combobox with a TextBlock it does show the DimName Field’s value, like this
<TextBox Text="{Binding DimName}"/>
What am I missing ?
Does your
DimNamecome directly from theDimensionslist?By default, if a ComboBox’s Items is set to a custom class, it will compare the
SelectedItemto an item in theItemSourceby reference. It will not match the item if they do not refer to the exact same object in memory, even if the object’s data is the same.To get around that you can either set
SelectedValueandSelectedValuePathinstead ofSelectedItemon your ComboBox, or you can overwrite theEquals()method of yourDimNameclass to return true if an object’s data is equalEdit
In regards to your comment below, is
DimNameaDimensionobject? If so then settingSelectedItemshould work fine. If it’s an long you’ll need to setSelectedValue, notSelectedItem. If it’s something else, you may need a converter to convert it into aDimensionobject