I have the SelectedIndex property of my ComboBox binded to a property in my ViewModel. Everytime a user selects an item from the ComboBox, nothing should appear in the SelectedItem area (The SelectedIndex should remain -1). To do this, I have tried the following:
cs
private int selectedIndexDoor;
public int SelectedIndexDoor
{
get { return selectedIndexDoor; }
set
{
selectedIndexDoor = -1;
OnPropertyChanged("SelectedIndexDoor");
}
}
xaml
<ComboBox Width="150"
materialDesign:HintAssist.Hint="Door"
ItemsSource="{Binding Doors}"
Margin="0, 0, 50, 0"
SelectedIndex="{Binding SelectedIndexDoor,
UpdateSourceTrigger=PropertyChanged}">
</ComboBox>
However it doesn't work. The value I manually set the index to is ignored. Why is this?
SelectedIndexDoor), it doesn't then read the value back and update the control. The "accepted" way of doing that is to start another thread that updates the vm property after the binding finishes updating it. If you want a viewmodel property to reject a change coming from the binding, have it throw an exception. The UI will treat that as a validation error -- probably not what you want. I think you may want to handle SelectedIndexChanged, and setSelectedItem=null;in the handler, or something. How are you using the selection from the combobox? - 15ee8f99-57ff-4f92-890c-b56153SelectedIndexDoorshould be the selected door index. It's true that you can be reasonably confident you won't end up doing that in this case, but it's a very good way to think about designing the two different types of classes: Couple them as loosely as possible. If somebody comes along and writes a new viewmodel for your view or vice versa, make his life maximally easy. - 15ee8f99-57ff-4f92-890c-b56153