Implementing a simple Master-Detail script for WPF in MVVM

I have a WPF application using MVVM. I have some user controls that should display the FirstName username, LastName and email in the three Textbox controls using simple data bindings.

The user control has a simple combo box in which the user selects an identifier for the user, and therefore the Person record with this identifier must be loaded (data taken from the database), and then the FirstName, LastName and email will be displayed in Textboxes.

I have a Usercontrol with combobox for identifiers and 3 text fields for three properties, a ViewModel class and a Model (person Class) class with three properties (FirstName, LastName and Email).

What is the easiest way to implement this behavior using MVVM (desirable)? any samples?

+3
source share
1 answer

I guess here, since your question is a bit vague that you are not quite sure how to combine the pieces. For simplicity, let us connect the ViewModel directly to a user control and get its binding.

, . . WPF .

UserControl :

public MyUserControl()
{
  DataContext = new MyViewModel();
}

UserControl 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}" />

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; }
}
+5

Source: https://habr.com/ru/post/1713549/


All Articles