Binding Up Nested UserComponent To it ViewModel - wpf

I have a WFP Project and i am using MVVM Pattern.
I have AddressView User control which i used in CustomerView UserControl.
<my:AddressVeiw Width="340" DataContext="AddressViewModel"/>
My AddressVeiw userControl has a AddressViewModel and CustomerView has a CustomerViewModel
Code for CustomerViewModel
public DelegateCommand<object> SaveCommand { get; set; }
private string firstName;
public string FirstName
{
get { return firstName; }
set {
firstName = value;
RaisePropertyChanged("FirstName");
SaveCommand.RaiseCanExecuteChanged();
}
}
private string lastName;
public string LastName
{
get { return lastName; }
set {
lastName = value;
RaisePropertyChanged("LastName");
SaveCommand.RaiseCanExecuteChanged();
}
}
private AddressViewModel addressViewModel;
public AddressViewModel AddressViewModel
{
get { return addressViewModel; }
set { addressViewModel = value; }
}
private string middleName;
public string Middlename
{
get { return middleName; }
set
{
middleName = value;
RaisePropertyChanged("MiddleName");
SaveCommand.RaiseCanExecuteChanged();
}
}
private string fullName;
public string FullName
{
get { return fullName; }
set {
fullName = value;
RaisePropertyChanged("FullName");
}
}
private void InitializeCommands()
{
SaveCommand = new DelegateCommand<object>(OnSaveCommand, CanSaveExcute);
}
private bool CanSaveExcute(object obj)
{
if (string.IsNullOrEmpty(firstName) ||string.IsNullOrEmpty(lastName))
return false;
return true;
}
private void OnSaveCommand(object obj)
{
FullName = FirstName + " " + LastName;
}
}
Code for AddressViewModel
private ObservableCollection<Country> countryList = new ObservableCollection<Country>();
public ObservableCollection<Country> CountryList
{
get { return countryList; }
set { countryList = value; }
}
public DelegateCommand<object> SaveCommand { get; set; }
private void Load()
{
try
{
CountryList = (new CountryRepository().GetAll());
}
catch (Exception ex)
{
OnSetStatusBarText("Error: " + ex.Message.ToString());
}
}
private void OnSetStatusBarText(string message)
{
var evt = eventAgg.GetEvent<StatusBarMessageEvent>();
evt.Publish(message);
}
private void InitializeCommands()
{
SaveCommand = new DelegateCommand<object>(OnSaveCommand, CanSaveExcute);
}
private bool CanSaveExcute(object obj)
{
return true;
}
private void OnSaveCommand(object obj)
{
}
Some how i can hook my AdddressViewModel To my AddressView, Customer Works fine...
What Must be done to resolve this problem?
Thanks

You need to use a binding expression for the DataContext of your AddressView. Instead of this...
<my:AddressVeiw Width="340" DataContext="AddressViewModel"/>
...try this...
<my:AddressVeiw Width="340" DataContext="{Binding AddressViewModel}"/>

You're close, but you need a binding:
<my:AddressVeiw Width="340" DataContext="{Binding AddressViewModel}"/>

Related

MVVM Datagrid Binding SelectedItem not updating

I'm new to WPF and MVVM and i've an applicaton that uses Entity Framework to connect to database and a datagrid to show the users of the application.
The users CRUD operations are made in a separate window and not in the datagrid.
My problems are related with the update of datagrid.
The insert operation is ok but the update is not.
View 1 (Users List):
<DataGrid Grid.Row="1"
ItemsSource="{Binding Users, Mode=TwoWay}"
SelectedItem="{Binding SelectedUser, Mode=TwoWay}"
AutoGenerateColumns="False"
CanUserAddRows="False">
</DataGrid>
ViewModel :
class UserListViewModel: NotificationClass
{
UserDBContext _db = null;
public UserListViewModel()
{
_db = new UserDBContext();
Users = new ObservableCollection<User>(_db.User.ToList());
SelectedUser = Users.FirstOrDefault();
}
private ObservableCollection<User> _users;
public ObservableCollection<User> Users
{
get { return _users; }
set
{
_users = value;
OnProprtyChanged();
}
}
private User _selectedUser;
public User SelectedUser
{
get
{
return _selectedUser;
}
set
{
_selectedUser = value;
OnProprtyChanged();
}
}
public RelayCommand Edit
{
get
{
return new RelayCommand(EditUser, true);
}
}
private void EditUser()
{
try
{
UserView view = new UserView();
view.DataContext = SelectedUser;
view.ShowDialog();
if (view.DialogResult.HasValue && view.DialogResult.Value)
{
if (SelectedUser.Id > 0){
User updatedUser = _db.User.First(p => p.Id == SelectedUser.Id);
updatedUser.Username = SelectedUser.Username; //this doesn't do nothing, object is already with the new username ?!
}
_db.SaveChanges();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
after _db.SaveChanges(), datagrid should not be updated ?
Model:
class UserDBContext: DbContext
{
public UserDBContext() : base("name=DefaultConnection")
{
}
public DbSet<User> User { get; set; }
}
View 2 (User detail)
public partial class UserView : Window
{
public UserView()
{
InitializeComponent();
}
private void SaveButton_Click(object sender, RoutedEventArgs e)
{
DialogResult = true;
}
}
User object
class User: NotificationClass
{
public int Id { get; set; }
public string Username { get; set; }
public string CreatedBy { get; set; }
public DateTime? CreatedOn { get; set; }
}
NotificationClass
public class NotificationClass : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged = delegate { };
public void OnProprtyChanged([CallerMemberName]string propertyName = null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
if i close and open view 1, the new username is updated..
could someone help ? thanks
Just implementing INotifyPropertyChanged isn't enough, you have to explicitly invoke PropertyChanged (or in your case OnPropertyChanged) when a property changed.
See also https://learn.microsoft.com/en-us/dotnet/framework/wpf/data/how-to-implement-property-change-notification
You can do it like so
class User : NotificationClass
{
private int _id;
private string _username;
private string _createdBy;
private DateTime? _createdOn;
public int Id
{
get => _id;
set
{
if (value == _id) return;
_id = value;
OnPropertyChanged();
}
}
public string Username
{
get => _username;
set
{
if (value == _username) return;
_username = value;
OnPropertyChanged();
}
}
public string CreatedBy
{
get => _createdBy;
set
{
if (value == _createdBy) return;
_createdBy = value;
OnPropertyChanged();
}
}
public DateTime? CreatedOn
{
get => _createdOn;
set
{
if (value.Equals(_createdOn)) return;
_createdOn = value;
OnPropertyChanged();
}
}
}
it worked ! many thanks #nosale !
what about the change made to SelectedUser being reflected in my context ?
if i do this :
SelectedUser.Username = "test";
User updatedUser = _db.User.First(p => p.Id == SelectedUser.Id);
i was thinking that SelectedUser object has the "test" username and updatedUser has the old username, but not .. updatedUser already have "test"

Prism INavigationAware Interface not invoking IsNavigationTarget

I am using prism 6 and on my application I have modules. I want to navigate to different views on different modules and I am using INavigationAware Interface. I can call OnNavigatedFrom every time I am navigating away from current view but when I enter a new view OnNavigatedTo is not fired which is giving me a headache. I will post my code from bootstrap to viewmodel for one module.
Bootstraper.cs
public class Bootstrapper : UnityBootstrapper
{
#region Members
private ILog _logger;
#endregion
#region Properties
#endregion
#region Methods
protected override DependencyObject CreateShell()
{
_logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
RegisterTypes();
return Container.Resolve<AppShell>();
}
protected override void InitializeShell()
{
App.Current.MainWindow = (Window)this.Shell;
App.Current.MainWindow.Show();
}
protected void RegisterTypes()
{
Container.RegisterType<ILogger, Log4NetLogger>(new InjectionConstructor(_logger));
Container.RegisterType<IEncryption, SymmetricEncryption>();
Container.RegisterType<IGetSavviUow, GetSavviUowMock>();
Container.RegisterType<ICustomAuthentication, MockCustomAuthentication>();
Container.RegisterType<ICustomPrincipal, CustomPrincipal>();
Container.RegisterType<IIdNumberValidation, IdNumberValidation>();
Container.RegisterType<ISalesValidation, SalesValidation>();
AutoMapperConfig.RegisterMappings();
}
protected override void ConfigureModuleCatalog()
{
ModuleCatalog.AddModule(new ModuleInfo()
{
InitializationMode = InitializationMode.WhenAvailable,
ModuleType = typeof(LoginModuleDefinition).AssemblyQualifiedName,
ModuleName = typeof(LoginModuleDefinition).Name
});
ModuleCatalog.AddModule(new ModuleInfo()
{
InitializationMode = InitializationMode.OnDemand,
ModuleType = typeof(AgentQueueModuleDefinition).AssemblyQualifiedName,
ModuleName = typeof(AgentQueueModuleDefinition).Name
});
ModuleCatalog.AddModule(new ModuleInfo()
{
InitializationMode = InitializationMode.OnDemand,
ModuleType = typeof(PreQualificationModuleDefinition).AssemblyQualifiedName,
ModuleName = typeof(PreQualificationModuleDefinition).Name
});
ModuleCatalog.AddModule(new ModuleInfo()
{
InitializationMode = InitializationMode.OnDemand,
ModuleType = typeof(SearchModuleDefinition).AssemblyQualifiedName,
ModuleName = typeof(SearchModuleDefinition).Name
});
ModuleCatalog.AddModule(new ModuleInfo()
{
InitializationMode = InitializationMode.OnDemand,
ModuleType = typeof(PlanSelectionModuleDefinition).AssemblyQualifiedName,
ModuleName = typeof(PlanSelectionModuleDefinition).Name
});
ModuleCatalog.AddModule(new ModuleInfo()
{
InitializationMode = InitializationMode.OnDemand,
ModuleType = typeof(BenefitsScriptModuleDefinition).AssemblyQualifiedName,
ModuleName = typeof(BenefitsScriptModuleDefinition).Name
});
ModuleCatalog.AddModule(new ModuleInfo()
{
InitializationMode = InitializationMode.OnDemand,
ModuleType = typeof(PersonalInfoModuleDefinition).AssemblyQualifiedName,
ModuleName = typeof(PersonalInfoModuleDefinition).Name
});
}
protected override void InitializeModules()
{
base.InitializeModules();
}
#endregion
#region Constructors
#endregion
}
ShellViewModel.cs
public class ShellViewModel : ViewModelBase
{
#region Members
private string _username;
private bool _isLoggedIn;
private string _viewName;
private bool _canCreateNewMembership;
private bool _canUpgrade;
private bool _canReinstate;
private bool _canContinue;
private ILogger _logger;
private IModuleManager _moduleManager;
private IRegionManager _regionManager;
private Guid _agentRefId;
#endregion
#region Properties
public string Username
{
get { return _username; }
set
{
SetProperty(ref _username, value);
}
}
public bool IsLoggedIn
{
get { return _isLoggedIn; }
set { SetProperty(ref _isLoggedIn, value); }
}
public string ViewName
{
get { return _viewName; }
set { SetProperty(ref _viewName, value); }
}
#endregion
#region Methods
private void InitDelegateCommands()
{
this.LogoutCommand = new DelegateCommand(Logout);
this.ContinueCommand = new DelegateCommand<string>(Continue, CanContinue);
this.CreateNewMembershipCommand = new DelegateCommand(CreateNewMembership, CanCreateNewMembership);
this.ExitApplicationCommand = new DelegateCommand(ExitApplication);
this.ReinstateCommand = new DelegateCommand(Reinstate, CanReinstate);
this.SaveAndExitCommand = new DelegateCommand(SaveAndExit);
this.SaveProgressCommand = new DelegateCommand(Save);
this.SetCallBackCommand = new DelegateCommand(SetCallBack);
this.UpgradeCommand = new DelegateCommand(Upgrade, CanUpgrade);
}
private bool CanContinue(string navigatingTo)
{
this.NavigatingToView = navigatingTo;
return _canContinue;
}
private void Continue(string currentView)
{
this.Aggregator.GetEvent<ContinueEvent>().Publish(
this.ViewNavigationList
.First(x =>
x.CurrentView == currentView).RequestedView);
}
private bool CanUpgrade()
{
return _canUpgrade;
}
private void Upgrade()
{
this.Aggregator.GetEvent<UpgradeEvent>().Publish(_agentRefId);
}
private void Logout()
{
ICustomPrincipal customPrincipal = Thread.CurrentPrincipal as ICustomPrincipal;
if (customPrincipal != null)
{
customPrincipal.CustomIdentity = new AnonymousIdentity();
this.Username = string.Empty;
this.IsLoggedIn = false;
ShowView(ModuleViewConstants.LoginView);
}
}
private void SetCallBack()
{
this.Aggregator.GetEvent<SetCallBackEvent>().Publish(_agentRefId);
}
private void Save()
{
this.Aggregator.GetEvent<SaveEvent>().Publish(_agentRefId);
}
private void SaveAndExit()
{
this.Aggregator.GetEvent<SaveEvent>().Publish(_agentRefId);
}
private bool CanReinstate()
{
return _canReinstate;
}
private void Reinstate()
{
this.Aggregator.GetEvent<ContinueEvent>().Publish(ModuleViewConstants.PlanSelectionView);
}
private bool CanCreateNewMembership()
{
return _canCreateNewMembership;
}
private void CreateNewMembership()
{
this.Aggregator.GetEvent<ContinueEvent>().Publish(ModuleViewConstants.PlanSelectionView);
}
private void ExitApplication()
{
this.Aggregator.GetEvent<ExitApplicationEvent>().Publish(_agentRefId);
}
private void OnLoggedOn(LoggedOnArgument args)
{
this.Username = args.Username;
this.IsLoggedIn = args.IsLoggedOn;
_agentRefId = args.AgentRefId;
LoadModules();
_regionManager.Regions[RegionConstants.QueueRegion].Context = _agentRefId;
ShowView(ModuleViewConstants.PreQualificationView);
}
private void LoadModules()
{
_moduleManager.LoadModule(typeof(AgentQueueModuleDefinition).Name);
_moduleManager.LoadModule(typeof(SearchModuleDefinition).Name);
_moduleManager.LoadModule(typeof(PreQualificationModuleDefinition).Name);
_moduleManager.LoadModule(typeof(PlanSelectionModuleDefinition).Name);
_moduleManager.LoadModule(typeof(BenefitsScriptModuleDefinition).Name);
_moduleManager.LoadModule(typeof(PersonalInfoModuleDefinition).Name);
}
private void ShowView(string view)
{
this.ViewName = view;
this.CurrentView = view;
_regionManager.RequestNavigate(
RegionConstants.OperationsRegion,
new Uri(view, UriKind.Relative));
}
private void AssingCanCreateNewMembership(bool canCreateMembership)
{
_canCreateNewMembership = canCreateMembership;
CreateNewMembershipCommand.RaiseCanExecuteChanged();
}
private void AssignCanContinue(bool canContinue)
{
_canContinue = canContinue;
ContinueCommand.RaiseCanExecuteChanged();
}
private void AssignCanUpgrade(bool canUpgrade)
{
_canUpgrade = canUpgrade;
UpgradeCommand.RaiseCanExecuteChanged();
}
private void AssignCanReinstate(bool canReinstate)
{
_canReinstate = canReinstate;
ReinstateCommand.RaiseCanExecuteChanged();
}
private void EventSubscriptions()
{
this.Aggregator.GetEvent<LoggedOnEvent>().Subscribe(OnLoggedOn);
this.Aggregator.GetEvent<ShowViewEvent>().Subscribe(ShowView);
this.Aggregator.GetEvent<CanCreateNewMembership>().Subscribe(AssingCanCreateNewMembership);
this.Aggregator.GetEvent<CanContinueEvent>().Subscribe(AssignCanContinue);
this.Aggregator.GetEvent<CanUpgradeEvent>().Subscribe(AssignCanUpgrade);
this.Aggregator.GetEvent<CanReinstateEvent>().Subscribe(AssignCanReinstate);
}
#endregion
#region Commands
public DelegateCommand LogoutCommand { get; set; }
public DelegateCommand ExitApplicationCommand { get; set; }
public DelegateCommand<string> ContinueCommand { get; set; }
public DelegateCommand SaveProgressCommand { get; set; }
public DelegateCommand SetCallBackCommand { get; set; }
public DelegateCommand SaveAndExitCommand { get; set; }
public DelegateCommand CreateNewMembershipCommand { get; set; }
public DelegateCommand ReinstateCommand { get; set; }
public DelegateCommand UpgradeCommand { get; set; }
#endregion
#region Events
#endregion
#region Construction
public ShellViewModel(
IRegionManager regionManager,
IUnityContainer container,
IEventAggregator aggregator,
IModuleManager moduleManager,
ILogger logger)
: base(aggregator, container)
{
_logger = logger;
_logger.Info("Starting Shell");
_moduleManager = moduleManager;
_regionManager = regionManager;
InitDelegateCommands();
EventSubscriptions();
}
#endregion
}
PreQualificationModule
PreQualificationModuleDefinition.cs
public class PreQualificationModuleDefinition : IModule
{
#region Members
private IRegionManager _regionManager;
private IUnityContainer _container;
#endregion
#region Properties
#endregion
#region Methods
public void Initialize()
{
_container.RegisterType<object, PreQualificationView>(ModuleViewConstants.PreQualificationView);
_regionManager.RegisterViewWithRegion(RegionConstants.OperationsRegion, typeof(PreQualificationView));
}
#endregion
#region Constructors
public PreQualificationModuleDefinition(
IRegionManager regionManager,
IUnityContainer container)
{
_regionManager = regionManager;
_container = container;
}
#endregion
}
PreQualificationViewModel.cs
public class PreQualificationViewModel : ViewModelBase, INavigationAware
{
#region Members
private string _name;
private int _selectedIdType;
private string _contactNumber;
private string _idNumber;
private DateTime? _dateOfBirth;
private int? _age;
private string _gender;
private string _passportNumber;
private bool _isCitizen;
private bool _isSearch;
private bool _showUserControl;
private bool _showPassportFields;
private bool _hasContactNumber;
private ObservableCollection<string> _genderList;
private int? _planId;
private IList<PolicyGrid> _policies;
private Principal _mainMember;
private Lead _lead;
private Membership _membership;
private IGetSavviUow _uow;
private IIdNumberValidation _idNumberValidation;
private ICustomPrincipal _principal;
private ISalesValidation _salesValidation;
private IRegionManager _regionManager;
#endregion
#region Properties
public string Name
{
get { return _name; }
set { SetProperty(ref _name, value); }
}
public int SelectedIdType
{
get { return _selectedIdType; }
set
{
SetProperty(ref _selectedIdType, value, this);
if (_selectedIdType == 2)
{
this.ShowPassportFields = true;
this.IsCitizen = false;
}
else
{
this.ShowPassportFields = false;
this.IsCitizen = true;
}
}
}
public ObservableCollection<KeyValuePair<int, string>> IdTypes
{
get
{
return new ObservableCollection<KeyValuePair<int, string>>()
{
new KeyValuePair<int, string>(1, "RSA ID Number"),
new KeyValuePair<int, string>(2, "Passport")
};
}
}
[Required]
public string ContactNumber
{
get { return _contactNumber; }
set
{
SetProperty(ref _contactNumber, value, this);
}
}
[IdValidation("SelectedIdType")]
[RequiredIf("SelectedIdType", 1)]
[Display(Name = "ID Number")]
public string IdNumber
{
get { return _idNumber; }
set
{
SetProperty(ref _idNumber, value, this);
if (_idNumberValidation.IsCitizen(_idNumber))
{
this.IsCitizen = true;
SetIdProperties();
}
}
}
[RequiredIf("SelectedIdType", 2)]
[Display(Name = "Date of Birth")]
public Nullable<DateTime> DateOfBirth
{
get { return _dateOfBirth; }
set
{
SetProperty(ref _dateOfBirth, value, this);
if (_dateOfBirth != null)
this.Age = DateTime.Today.Year - _dateOfBirth.Value.Year;
}
}
[AgeMinMax("PlanId")]
public Nullable<int> Age
{
get { return _age; }
set
{
SetProperty(ref _age, value, this);
}
}
[RequiredIf("SelectedIdType", 2)]
public string Gender
{
get { return _gender; }
set
{
SetProperty(ref _gender, value, this);
}
}
public ObservableCollection<string> GenderList
{
get { return _genderList; }
set
{
SetProperty(ref _genderList, value);
}
}
[RequiredIf("SelectedIdType", 2)]
[Display(Name = "Passport Number")]
public string PassportNumber
{
get { return _passportNumber; }
set
{
SetProperty(ref _passportNumber, value, this);
}
}
public bool IsCitizen
{
get { return _isCitizen; }
set { SetProperty(ref _isCitizen, value, this); }
}
public bool IsSearch
{
get { return _isSearch; }
set { SetProperty(ref _isSearch, value, this); }
}
public bool ShowUserControl
{
get { return _showUserControl; }
set { SetProperty(ref _showUserControl, value, this); }
}
public bool ShowPassportFields
{
get { return _showPassportFields; }
set { SetProperty(ref _showPassportFields, value, this); }
}
public bool HasContactNumber
{
get { return _hasContactNumber; }
set { SetProperty(ref _hasContactNumber, value, this); }
}
public Nullable<int> PlanId
{
get { return _planId; }
set { _planId = value; }
}
public IList<PolicyGrid> Policies
{
get { return _policies; }
set { SetProperty(ref _policies, value); }
}
#endregion
#region Methods
private void SetIdProperties()
{
this.Age = _idNumberValidation.GetAge(DateTime.Today, this.IdNumber);
this.DateOfBirth = _idNumberValidation.GetDateOfBirth(this.IdNumber);
this.Gender = _idNumberValidation.GetGender(this.IdNumber);
}
private void GetLeadInfo(int callQueueId)
{
ClearProperties();
var callQueue = _uow.RepoCallQueue.GetLeadByCallQueueIdRefId(callQueueId, _principal.CustomIdentity.RefId);
this.ShowUserControl = true;
var leadCallQueue = callQueue.Lead_CallQueue.FirstOrDefault(x => x.CallQueueId == callQueueId);
_lead = leadCallQueue.Lead;
this.Name = _lead.FirstName + " " + _lead.Surname;
this.IdNumber = _lead.IdNumber;
this.PlanId = _lead.PlanId;
if (!string.IsNullOrEmpty(_lead.Mobile))
{
this.HasContactNumber = true;
this.ContactNumber = _lead.Mobile;
}
if (!string.IsNullOrEmpty(_lead.IdNumber) &&
_idNumberValidation.IsCitizen(_lead.IdNumber))
{
this.SelectedIdType = 1;
}
else if (!string.IsNullOrEmpty(_lead.IdNumber))
{
this.SelectedIdType = 2;
}
}
private void ClearProperties()
{
this.IdNumber = string.Empty;
this.DateOfBirth = null;
this.Gender = null;
this.Age = null;
}
private void SearchedMembership(SearchArgs arg)
{
ClearProperties();
this.ShowUserControl = true;
List<Membership> memberships = new List<Membership>();
if (!string.IsNullOrEmpty(arg.SearchedId))
{
switch (arg.SearchingType)
{
case 1:
//Membership Number
memberships = _uow.RepoMembership.GetMembershipsByMembershipNumber(Convert.ToInt32(arg.SearchedId)).ToList();
break;
case 2:
//ID Number
memberships = _uow.RepoMembership.GetMembershipsByIdNumber(arg.SearchedId).ToList();
break;
case 3:
//Passport
memberships = _uow.RepoMembership.GetMembershipsByPassport(arg.SearchedId).ToList();
break;
default:
throw new ArgumentException("Uknown Searching type!");
}
_mainMember = memberships.FirstOrDefault().Principal;
if(memberships.Count > 0)
this.Policies = memberships.Select(x => new PolicyGrid(
x.Id,
_uow.Plan.GetById(x.PlanId.Value).Description,
_uow.MembershipStatus.GetById(x.MembershipStatusId).Description,
x.CommenceDate.HasValue?x.CommenceDate.Value.ToString("dd/MM/yyyy") : null,
x.ResignationDate.HasValue ? x.ResignationDate.Value.ToString("dd/MM/yyyy") : null)).ToList();
this.Name = _mainMember.FirstName + " " + _mainMember.Surname;
this.IdNumber = _mainMember.IdNumber;
this.PlanId = _uow.RepoMembership.GetLatestMembership(this.IdNumber).PlanId;
if (!string.IsNullOrEmpty(_mainMember.Mobile))
{
this.HasContactNumber = true;
this.ContactNumber = _mainMember.Mobile;
}
if (!string.IsNullOrEmpty(_mainMember.IdNumber) &&
_idNumberValidation.IsCitizen(_mainMember.IdNumber))
{
this.SelectedIdType = 1;
}
else if (!string.IsNullOrEmpty(_mainMember.IdNumber))
{
this.SelectedIdType = 2;
}
}
}
private void RaiseCommands(object value)
{
if (!string.IsNullOrEmpty(this.IdNumber))
{
if (!_salesValidation.IdNumberExists(this.IdNumber) && !this.HasErrors)
{
this.Aggregator.GetEvent<CanCreateNewMembership>().Publish(true);
}
else if (_salesValidation.IdNumberExists(this.IdNumber) &&
!_salesValidation.IncompleteApplication(this.IdNumber) &&
!_salesValidation.CanUpgrade(this.IdNumber) &&
!_salesValidation.CanReInstate(this.IdNumber))
{
//this.Aggregator.GetEvent<CanCreateNewMembership>().Publish(true);
}
else
{
this.Aggregator.GetEvent<CanCreateNewMembership>().Publish(false);
}
if (_salesValidation.IdNumberExists(this.IdNumber) &&
!this.HasErrors && _salesValidation.IncompleteApplication(this.IdNumber))
{
this.Aggregator.GetEvent<CanContinueEvent>().Publish(true);
}
else
{
this.Aggregator.GetEvent<CanContinueEvent>().Publish(false);
}
if (_salesValidation.IdNumberExists(this.IdNumber) &&
_salesValidation.CanUpgrade(this.IdNumber))
{
this.Aggregator.GetEvent<CanUpgradeEvent>().Publish(true);
}
else
{
this.Aggregator.GetEvent<CanUpgradeEvent>().Publish(false);
}
if (_salesValidation.IdNumberExists(this.IdNumber) &&
_salesValidation.CanReInstate(this.IdNumber))
{
this.Aggregator.GetEvent<CanReinstateEvent>().Publish(true);
}
else
{
this.Aggregator.GetEvent<CanReinstateEvent>().Publish(false);
}
if (this.HasErrors)
{
this.Aggregator.GetEvent<CanCreateNewMembership>().Publish(false);
this.Aggregator.GetEvent<CanContinueEvent>().Publish(false);
this.Aggregator.GetEvent<CanUpgradeEvent>().Publish(false);
this.Aggregator.GetEvent<CanReinstateEvent>().Publish(false);
}
}
}
private void Continue(string view)
{
if (view == ModuleViewConstants.PlanSelectionView)
this.Aggregator.GetEvent<ShowViewEvent>().Publish(
ModuleViewConstants.PlanSelectionView);
}
private void EventSubscriptions()
{
this.Aggregator.GetEvent<LoadLeadInfoEvent>().Subscribe(GetLeadInfo);
this.Aggregator.GetEvent<RaiseCommandAndEventsEvent>().Subscribe(RaiseCommands);
this.Aggregator.GetEvent<SearchEvent>().Subscribe(SearchedMembership);
this.Aggregator.GetEvent<ContinueEvent>().Subscribe(Continue);
this.Aggregator.GetEvent<SaveEvent>().Subscribe(SaveProgress);
}
bool INavigationAware.IsNavigationTarget(NavigationContext navigationContext)
{
_membership = GetMembership(navigationContext);
return _membership == null;
}
private Membership GetMembership(NavigationContext navigationContext)
{
if (navigationContext.NavigationService.Region.Context != null &&
navigationContext.NavigationService.Region.Context is Membership)
return (Membership)navigationContext.NavigationService.Region.Context;
return null;
}
void INavigationAware.OnNavigatedFrom(NavigationContext navigationContext)
{
var refId = (Thread.CurrentPrincipal as ICustomPrincipal).CustomIdentity.RefId;
this.SaveProgress(refId);
if (_membership != null)
{
navigationContext.NavigationService.Region.Context = _membership;
}
}
void INavigationAware.OnNavigatedTo(NavigationContext navigationContext)
{
}
private void SaveProgress(Guid refId)
{
var agentId = _uow.User.GetByRef(refId).Id;
_mainMember = new Principal();
if (_lead != null)
Mapper.Map(_lead, _mainMember);
if (_membership == null)
_membership = new Membership(
Guid.NewGuid(),
_lead.PlanId.HasValue?_lead.PlanId : null,
null,
null,
null,
DateTime.Now,
agentId,
_mainMember.Id,
(int)BillingStatusEnum.BAFP,
(int)MembershipStatusEnum.PWS,
null,
null,
null);
if (_mainMember != null)
{
//To Take out when Db is working
var principalId = _uow.Principal.GetAll().Max(x => x.Id);
_mainMember.Id = principalId + 1;
_membership.Principal = _mainMember;
}
//To Take out when Db is working
var id = _uow.Membership.GetAll().Max(x => x.Id);
_membership.Id = id + 1;
//===================================================\\
}
#endregion
#region Commands
#endregion
#region EventHandlers
#endregion
#region Constructors
public PreQualificationViewModel(
IEventAggregator aggregator,
IUnityContainer container,
IRegionManager regionManager,
IGetSavviUow uow,
IIdNumberValidation idNumberValidation,
ISalesValidation salesValidation) :
base(aggregator, container)
{
_uow = uow;
_regionManager = regionManager;
_principal = Thread.CurrentPrincipal as ICustomPrincipal;
_idNumberValidation = idNumberValidation;
_salesValidation = salesValidation;
EventSubscriptions();
this.GenderList = new ObservableCollection<string>()
{
"Male",
"Female"
};
}
#endregion
}
Please Help!!!

How to add sublist in wpf using mvvm?

namespace colourchanges
{
public class Group
{
public string Name { get; set; }
//its a class for adding parent list using group class
}
public class EmployeeTree : INotifyPropertyChanged
{
public EmployeeTree()
{
this.GroupStaff = new List<Group>();
GroupStaff.Add(new Group { Name = "Designers" });
GroupStaff.Add(new Group { Name = "Developers" });
GroupStaff.Add(new Group { Name = "Managers" });
//here we are declaring list for adding parent list
}
private List<Group> _GroupStaff;
public List<Group> GroupStaff
{
get { return _GroupStaff; }
set
{
_GroupStaff = value;
RaisePropertyChanged("GroupStaff");
}
}
//creates a list for parentlist
private Group _selectedGroupStaff;
public Group selectedGroupStaff
{
get { return _selectedGroupStaff; }
set
{
_selectedGroupStaff = value;
if (selectedGroupStaff.Name == "Designers")
{
City = "Chennai";
Country = "India";
Email = "Designer#gmail.com";
MobileNo = 9094117917;
Address = "Annanagar";
}
else if (selectedGroupStaff.Name == "Developers")
{
City = "Trichy";
Country = "India";
Email = "Developer#gmail.com";
MobileNo = 9094667878;
Address = "Koyambedu";
}
else if (selectedGroupStaff.Name == "Managers")
{
City = "Salem";
Country = "India";
Email = "Manager#gmail.com";
MobileNo = 9094154678;
Address = "Arumbakkam";
}
RaisePropertyChanged("selectedGroupStaff");
}
}//for selecting parent list in order to bind to textbox
private string _City;
private string _Country;
private string _Email;
private long _MobileNo;
private string _Address;
//properties of parent list to bind to textbox
public string City
{
get { return _City; }
set
{
_City = value;
RaisePropertyChanged("City");
}
}
public string Country
{
get { return _Country; }
set
{
_Country = value;
RaisePropertyChanged("Country");
}
}
public string Email
{
get { return _Email; }
set
{
_Email = value;
RaisePropertyChanged("Email");
}
}
public long MobileNo
{
get { return _MobileNo; }
set
{
_MobileNo = value;
RaisePropertyChanged("MobileNo");
}
}
public string Address
{
get { return _Address; }
set
{
_Address = value;
RaisePropertyChanged("Address");
}
}
///raise property changed event handler code
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
//how to add sub list for designers developers and managers in the constructor
Let the following be your Model class
public class Group
{
private string _City;
private string _Country;
private string _Email;
private long _MobileNo;
private string _Address;
public Group()
{
Items = new ObservableCollection<Group>();
}
public ObservableCollection<Group> Items { get; set; }
}
and at the ViewModel's constructor, you can add the Items.
public EmployeeTree()
{
this.GroupStaff = new List<Group>();
Group rootGroup = new Group(){Name ="Manager"};
Group childGroup = new Group(){Name = "Developer"};
rootGroup.Items.Add(childGroup);
this.GroupStaff.Add(rootGroup);
}
This is for Hierarchical structure. Hope you are looking for this.
And your XAML should be like this
<TreeView Name="GroupTreeView">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Items}">
<TextBlock Text="{Binding Name}" />
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>

DisplayMemberPath databinding

I have a puzzled problem of databinding in WPF.
There is a listbox in XAML which it has linked with ItemSource,
but when it runs, it shows the lists of class names.
so I have applied to DisplayMemberPath, but it doesn't helpful.
and also I'm wondering how I can access inside class from generic class.
Thanks.
result
puzzled.Member
puzzled.Member
puzzled.Member
puzzled.Member
<DockPanel>
<ListBox Name="lbxMbrList" DockPanel.Dock="Left" Width="200" Padding="10"></ListBox>
<ContentControl />
</DockPanel>
private void Window_Loaded(object sender, RoutedEventArgs e)
{
members.Add(new Member("superman", "123-1234567", "address1"));
members.Add(new Member("batman", "111-111111", "address2"));
members.Add(new Member("goodman", "222-222222", "address3"));
members.Add(new Member("badman", "333-333333", "address4"));
lbxMbrList.ItemsSource = members;
lbxMbrList.DisplayMemberPath = members.MemberDetails; //<<it won't helpful
//var i = members.member.Name; //<<how can I access inside class?
//if (i == "superman")
//{
// MessageBox.Show("superman");
//}
}
public class Member
{
private string _name;
private string _phone;
private string _address;
public string Name { get { return _name; } set { _name = value; } }
public string Phone { get { return _phone; } set { _phone = value; } }
public string Address { get { return _address; } set { _address = value; } }
public Member() { }
public Member(string name, string phone, string address)
{
_name = name; _phone = phone; _address = address;
}
public string lbxMember
{
get { return string.Format("{0} - {1}", Name, Phone, Address); }
}
}
class MemberList : IEnumerable<Member>
{
private ObservableCollection<Member> memberList = new ObservableCollection<Member>();
public Member this[int i]
{
get {return memberList[i];}
set {memberList[i] = value;}
}
public void Add(Member member)
{
memberList.Add(member);
}
public void Remove(Member member)
{
memberList.Remove(member);
}
public IEnumerator<Member> GetEnumerator()
{
return memberList.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }
public Member member { get; set; } //<< it think I has misunderstood it
public string MemberDetails
{
get
{ return string.Format("{0} - {1}", member.Name, member.Phone, member.Address); }
}
}
You are assigning the output of your MemberDetails property to the DisplayMemberPath. Instead, you need to assign the name of the property as a string.
lbxMbrList.DisplayMemberPath = "MemberDetails";
For what its worth, this will be easier to work with if you use an ItemTemplate in the ListBox.
[Edit]
Also, as #Blam mentions in his answer, your MemberDetails property is defined in the wrong class, it needs be in the Member class.
lbxMbrList.DisplayMemberPath = "lbxMember";
or
lbxMbrList.DisplayMemberPath = "MemberDetails";
And MemberDetails need to be a property of Member (not MemberList)

Binding properties in two viewmodels in a two way manner

I'm starting Caliburn Micro development and I have thought of an architecture where a viewmodel has properties, injected by MEF, which are other viewmodels. That way I can use contentcontrols in the view to position them the way I want.
public class ContactsProfileViewModel : Conductor<IContentItem>, IContactsModuleViewModel, IModule, IPartImportsSatisfiedNotification
{
private string name;
private string nameCaption;
private ISingleLineTextContentItem firstName;
private ISingleLineTextContentItem lastName;
public ContactsProfileViewModel()
{
this.DisplayName = "Contact Tab";
}
public string Name
{
get
{
return this.name;
}
set
{
this.name = value;
this.NotifyOfPropertyChange(() => Name);
}
}
public string NameCaption
{
get
{
return this.nameCaption;
}
set
{
this.nameCaption = value;
this.NotifyOfPropertyChange(() => NameCaption);
}
}
[Import(typeof(ISingleLineTextContentItem))]
public ISingleLineTextContentItem FirstName
{
get { return this.firstName; }
set
{
this.firstName = value;
this.NotifyOfPropertyChange(() => FirstName);
}
}
[Import(typeof(ISingleLineTextContentItem))]
public ISingleLineTextContentItem LastName
{
get { return this.lastName; }
set
{
this.lastName = value;
this.NotifyOfPropertyChange(() => LastName);
}
}
The viewmodel of SingleLineTextContentItem looks like this:
[Export(typeof(ISingleLineTextContentItem))]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class SingleLineTextContentItemViewModel : PropertyChangedBase, ISingleLineTextContentItem
{
private string textBoxText;
private string caption;
public string TextBoxText
{
get { return textBoxText; }
set
{
textBoxText = value;
this.NotifyOfPropertyChange(() => TextBoxText);
}
}
public string Caption
{
get { return caption; }
set
{
this.caption = value;
this.NotifyOfPropertyChange(() => Caption);
}
}
}
Now, I need a way to bind the NameCaption property to the Caption property in a two-way manner. Is that possible? I'm I on the right track with this or is there a better way to do this?
Thanks,
Roland
What I do is instead of having a backing field just route to the other view model
public string NameCaption
{
get
{
return FirstName.Caption;
}
set
{
FirstName.Caption = value;
this.NotifyOfPropertyChange(() => NameCaption);
}
}
However if the Caption property on the ISingleLineTextContentItem can get set independently then you need to register changes on the event and have the view model listen to changes. So instead you need somthing along the lines of:
public string NameCaption
{
get
{
return FirstName == null ? string.Empty : FirstName.Caption;
}
set
{
if(FirstName != null)
FirstName.Caption = value;
}
}
[Import(typeof(ISingleLineTextContentItem))]
public ISingleLineTextContentItem FirstName
{
get { return this.firstName; }
set
{
if(this.FirstName != null)
this.FirstName.PropertyChanged -= FirstNameChanged;
this.firstName = value;
if(this.FirstName != null)
this.FirstName.PropertyChanged += FirstNameChanged;
this.NotifyOfPropertyChange(() => FirstName);
this.NotifyOfPropertyChange(() => NameCaption);
}
}
private void FirstNameChanged(object sender, PropertyChangedEventArgs e)
{
if(e.PropertName == "Caption")
this.NotifyOfPropertyChange(() => NameCaption);
}
Since either the Caption property or the FirstName property can change then we need to raise the event in the FirstName property and in the handler.

Resources