I have a MVVM project with a View and a ViewModel in its DataContext
.
In this project I have a class ComboBoxCustom
which inherits from ComboBox
. I define some additional functionality in my ComboBoxCustom
class.
To this ComboBoxCustom
class I assign a control template to define its appearance.
The (simplified) style defining the (simplified) control template looks like:
<Style TargetType="{x:Type lib:ComboBoxCustom}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type lib:ComboBoxCustom}">
<StackPanel>
<TextBlock Text="{TemplateBinding TextPropertyInComboBoxCustom}"/>
<ComboBox DataContext="{TemplateBinding DataContext}"
ItemsSource="{TemplateBinding ItemsSource}"
DisplayMemberPath="{TemplateBinding DisplayMemberPath}"
SelectedValuePath="{TemplateBinding SelectedValuePath}"
SelectedValue="{TemplateBinding SelectedValue}"
SelectedItem="{TemplateBinding SelectedItem}"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Which resides in a ResourceDictionary
. The real control template has some additional features which are left out since they are not relevant for the question.
I use this ComboBoxCustom
control in my View using:
<lib:ComboBoxCustom ItemsSource="{Binding MyObservableCollectionOfMyObjects}"
TextPropertyInComboBoxCustom="MyText"
DisplayMemberPath="MyDescription"
SelectedValuePath="MyValue"
SelectedItem="{Binding SelectedMyObject, Mode=TwoWay}"/>
The view is ok, and all items get loaded in the ComboBox which I can select.
The problem is that when I select a different item in the ComboBox, the property SelectedMyObject
in my ViewModel does not get updated and consequently its setter is not called. Therefore, the (correct) information about the selected object is not available in my ViewModel.
When I use <ComboBox .../>
(without the TextPropertyInComboBoxCustom
property) instead of <lib:ComboBoxCustom .../>
everything works just fine but then I don't have the additional functionality defined in ComboBoxMessage
which I need.
Can anyone tell me what is wrong and how to fix this issue so I can use ComboBoxMessage
in my view? Preferably without breaking the MVVM pattern.
Thank you!