I have a WPF application using MVVM. I have some user controls that should show a Person FirstName, LastName and email in 3 Textbox controls using simple databinding.
The User Control has a simple combobox where the user selects the ID for the user and therefore the Person Record with that ID should be loaded (its data fetched from the database) and then the FirstName, LastName and Email will display in the textBoxes.
I have a Usercontrol with the combobox for the IDs and 3 textboxes for the three properties, a ViewModel Class and a Model class (person Class) with the three properties (FirstName, LastName and Email).
What is the simplest way to implement this behavior using MVVM(preferably)? any samples?
I'm guessing here since your question is a little vague that you're not quite sure how to hook the pieces together. For simplicity's sake let us hook the ViewModel directly to the user control and get it all binding.
As long as your view model is populated with the correct set of People, all the binding below will handle the data and show the correct data. Take note of the two-way binding for the selected item in the combobox. That allows WPF to send back the new selected item to the viewmodel.
In the UserControl's code behind:
public MyUserControl()
{
DataContext = new MyViewModel();
}
In the UserControl's XAML:
<ComboBox ItemsSource="{Binding AllPeople}" SelectedItem="{Binding SelectedItem, Mode=TwoWay}" />
<TextBox Text="{Binding SelectedItem.LastName}" />
<TextBox Text="{Binding SelectedItem.FirstName}" />
<TextBox Text="{Binding SelectedItem.EmailName}" />
Your ViewModel:
private IEnumerable<Person> _allPeople;
public IEnumerable<Person> AllPeople
{
get { return _allPeople; }
set
{
if (_allPeople != value)
{
_allPeople = value;
NotifyPropertyChanged("AllPeople");
}
}
}
private Person _selectedItem;
public Person SelectedItem
{
get { return _selectedItem; }
set
{
if (!_selectedItem != value)
{
_selectedItem = value;
NotifyPropertyChanged("SelectedItem");
}
}
}
private void NotifyPropertyChanged(string propertyName)
{
if ( PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName);
}
}
}
public class Person
{
public int PersonId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With