Reputation: 131
Model:
class UserModel
{
public string FirstName { get; set; }
}
Service:
class UserService
{
private async Task<string> DirectoryEntry()
{
SearchResult rs = await Task.Run(() =>
{
DirectoryEntry de = new DirectoryEntry("xxx");
DirectorySearcher ds = new DirectorySearcher(de)
{
Filter = "(&((&(objectCategory=Person)(objectClass=User)))(sAMAccountName=" + "xxx" + "))",
SearchScope = SearchScope.Subtree
};
return ds.FindOne();
});
var value = (rs.GetDirectoryEntry().Properties["businessCategory"].Value ?? "BRAK").ToString();
return value;
}
}
ViewModel:
class UserViewModel : INotifyPropertyChanged
{
UserModel user = new UserModel();
public string FirstName
{
??
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChange(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
So, how to pass value
to ViewModel?
I checked some examples but I can't achieve it between Service and VM.
I totally don't know how to relate between them.
Or maybe is it incorrect use of mvvm?
Upvotes: 0
Views: 654
Reputation: 169420
Provided that your service method actually returns a value, the view model may do whatever it wants with this value like for example assigning it to a property of the UserModel
or a property of itself assuming the types match.
In general, the view model has a reference to the service:
class UserViewModel : INotifyPropertyChanged
{
readonly UserService service = new UserService();
//call a method on the service in any method of the view model
}
In the above code, the view model has a strong reference to the implementation of the service. It's more common to inject the view model with an interface that the service implements:
class UserViewModel : INotifyPropertyChanged
{
readonly IUserService _service;
public UserViewModel(IUserService service) => _service = service;
}
You can then switch implementation at runtime. You may for example want to test your view model with a mock of the service, but use a "real" service implementation when running your actual application.
Upvotes: 1