Reputation: 67
I have a wpf project with a ComboBox
. The items there inside are filled in dynamically. So it is bound to a model which contains a Label
and a Command.
If the User selects an item in the Dropdown / ComboBox
the Command should be executed. I tried it with a DataTemplate
containing a TextBlock
and a Hyperlink
for the Command. But the Command will only execute if a select the Label
(Hyperlink
) and not if I click on the whole item.
<ComboBox ItemsSource="{Binding Path=States}" SelectedItem="{Binding CurrentState}" >
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock>
<Hyperlink Command="{Binding Command}" TextDecorations="None" Foreground="Black">
<TextBlock Text="{Binding Path=Label}"/>
</Hyperlink>
</TextBlock>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
So the question is now, how can I bind my Command to a ComboBoxItem
?
Upvotes: 0
Views: 949
Reputation: 169160
A ComboBoxItem
has no Command
property but you could execute the command from the setter of the CurrentState
property:
private State _currentState;
public State CurrentState
{
get { return _currentState; }
set
{
_currentState = value;
if (_currentState != null)
{
_currentState.Command.Execute(null);
}
}
}
This property will be set whenever you select an item in the ComboBox
. The other option would be to handle the SelectionChanged
event in the view.
Upvotes: 1