I have a form with some fields and two combo boxes. My view model contains some instances of User class, which contains name and profile attributes.
ViewModel
public class UserViewModel: INotifyPropertyChanged
{
private ObservableCollection<User> usersList = new ObservableCollection<User>();
private User selectedUser = new User();
private User newUser = new User();
public UserViewModel()
{
}
public ObservableCollection<User> UsersList
{
get
{
return this.usersList;
}
set
{
this.usersList = value;
this.OnPropertyChanged();
}
}
public User SelectedUser
{
get
{
return this.selectedUser;
}
set
{
this.selectedUser = value;
this.OnPropertyChanged();
}
}
public User NewUser
{
get
{
return this.newUser;
}
set
{
this.newUser = value;
this.OnPropertyChanged();
}
}
private void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
Code-behind
this.userViewModel = new UserViewModel();
this.DataContext = this.userViewModel;
XAML
<-- The DataContext for this ComboBox is the entire UserViewModel -->
<ComboBox
Height="Auto"
Width="Auto"
IsEditable="True"
IsTextSearchCaseSensitive="False"
SelectedItem="SelectedUser">
<ComboBoxItem Content="Mary" IsSelected="True"></ComboBoxItem>
<ComboBoxItem Content="John"></ComboBoxItem>
</ComboBox>
If I select an user from the first combobox, all form fields get filled with the existing data. Whatever user I select, it's going to be saved in SelectedUser through SelectedItem property.
<Grid>
<Grid.DataContext>
<PriorityBinding>
<Binding Path="SelectedUser" Converter="{StaticResource NullToDependencyPropertyUnsetConverter}" />
<Binding Path="NewUser" />
</PriorityBinding>
</Grid.DataContext>
[...]
<-- The DataContext for this ComboBox will be SelectedUser or NewUser, depending on the case -->
<ComboBox
Name="profileComboBox"
Height="Auto"
Width="Auto"
IsEditable="True"
IsTextSearchCaseSensitive="False"
SelectedItem="Profile">
<ComboBoxItem Content="User" IsSelected="True"></ComboBoxItem>
<ComboBoxItem Content="Admin"></ComboBoxItem>
</ComboBox>
[...]
</Grid>
The ComboBox will have SelectedUser or NewUser as DataContext depending on whether SelectedUser is null or not. Then, whatever profile I select, it's going to be saved in Profile attribute of the previously selected user through SelectedItem property.
My problem is that the second combobox should select automatically the corresponding profile ("User" or "Admin") of the user just selected in the first combobox. Could this be achieved only using XAML?