I have a ComboBox. When users try change the selectedItem on the ComboBox, I want a MessageBox to pop up and confirm whether or not they want to change their selection. If not, the selection should not change. This is what I originally had:
SelectSiteView (XAML):
<ComboBox Name="SiteSelectionComboBox"
ItemsSource="{Binding SiteList}"
SelectedItem="{Binding SelectedSite}"/>
SelectSiteViewModel:
private List<string> siteList;
public List<string> SiteList
{
get { return siteList; }
set { siteList = value;
OnPropertyChanged();
}
}
private string selectedSite;
public string SelectedSite
{
get { return selectedSite; }
set {
if (CanChangeSite())
{
selectedSite = value;
OnPropertyChanged();
}
//if false, I DONT want the combobox to change it's selection.
//What I end up getting is a mismatch. The SelectedSite never gets updated to the new 'value', but the ComboBox still changes
}
}
private bool CanChangeSite()
{
MessageBoxResult result = MessageBox.Show("Are you sure?", "WARNING", MessageBoxButton.YesNo, MessageBoxImage.Question);
if (result == MessageBoxResult.Yes)
return true;
else return false;
}
I couldn't get that to work. I'm guessing since the binding is two-ways, even though I don't update my SelectedSite value, the ComboBox still changes the SelectedItem value from the UI, leading to a case where my binding can be mismatched.
I then moved forward to try and handle it the SelectionChanged event and had no luck. Here's how I tried Implementing it:
SelectSiteView (XAML):
xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
<ComboBox Name="SiteSelectionComboBox"
ItemsSource="{Binding SiteList}"
SelectedItem="{Binding SelectedSite}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<i:InvokeCommandAction Command="{Binding SelectionChangedCommand}" PassEventArgsToCommand="True"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</ComboBox>
SelectSiteViewModel:
public ICommand SelectionChangedCommand { get; set; }
public SelectSiteViewModel(MainViewModel main)
{
SelectionChangedCommand = new RelayCommand(o => SelectionChangedAction(o));
}
public void SelectionChangedAction(object param)
{
MessageBox.Show("selection changed command activated, param = " + param.ToString());
if (param == null)
MessageBox.Show("NULL");
//MessageBox.Show("Added item: " + param.AddedItems[0]);
//DOESNT WORK
}
I try passing in my ComboBox selection event arguments as a parameter to the ViewModel. When I print its ToString value, I get: "System.Windows.Controls.SelectionChangedEventArgs" and on the debugger, I can see that it has "AddedItems" and "RemovedItems" properties that I'm interested in. However, I can't access these items. Is it because the object isn't passed correctly? How would I go about accessing these items so that I can reject the change in the comboBox? Is using this event handler the best way to go about doing this?
I saw a solution using MVVMLite, I would prefer not to use any additional dependencies if possible. Thanks in advance!