Reputation: 11
I'm creating a customer care program using WPF MVVM pattern I created a registration window and a customer information window I want to bring the value of the data grid of the customer information window to the text box of the creation window
This is information ViewModel
public class MainViewModel : ObservableObject
{
private MemberInfo selectedCustomer = new MemberInfo();
public MemberInfo SelectedCustomer
{
get => selectedCustomer;
set
{
SetProperty(ref selectedCustomer, value);
RegisterViewModel RV = new RegisterViewModel();
if (value != null)
{
RV.Name = selectedCustomer.Name;
}
}
}
}
This is Creat ViewModel
public class RegisterViewModel : ObservableObject
{
private string name = "";
public string Name
{
get => this.name;
set => SetProperty(ref this.name, value);
}
}
If I use it like this, the value goes over only set, and there is no value to execute the get
Upvotes: 1
Views: 115
Reputation: 8518
If I use it like this, the value goes over only set, and there is no value to execute the get
Not entirely sure I understood this correctly, but you could pass a MemberInfo
object to the constructor of the RegisterViewModel
and expose it to the view via a read-only property.
So, the RegisterViewModel
becomes:
public class RegisterViewModel : ObservableObject
{
public RegisterViewModel(MemberInfo member)
{
Member = member;
}
public MemberInfo Member { get; }
}
Thus in the MainViewModel
:
public MemberInfo SelectedCustomer
{
get => selectedCustomer;
set
{
SetProperty(ref selectedCustomer, value);
RegisterViewModel RV = new RegisterViewModel(selectedCustomer);
}
}
The view then binds to:
Text = "{Binding Path=Member.Name, Mode=TwoWay}"
Edit
Since the RegisterViewModel
is expecting a MemberInfo
object, you cannot register it and simply call the GetService<T>
method.
What I usually do in this case, I make use of the ActivatorUtilities.CreateInstance which is part of the Microsoft.Extensions.DependencyInjection.Abstractions
package.
Through an extension method:
public static T Create<T>(this IServiceProvider provider, params object[] args) where T : class
{
return ActivatorUtilities.CreateInstance<T>(provider, args);
}
Which can then be called:
this.DataContext = App.Current.Services.Create<RegisterViewModel>(member);
This way, if the RegisterViewModel
is expecting additional registered services through the constructor, those will be resolved by the container.
Upvotes: 1