Prism INavigationAware Interface not invoking IsNavigationTarget - wpf

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!!!

Related

TableView with custom type combobox

I would like to create a TableView where its columns have reference to type:
private Indicators(String tl, WindowsItem chrt, String pne, Boolean sel) {
this.tool_col = new SimpleStringProperty(tl);
if (chrt == null) {
this.chart_col = new SimpleStringProperty("");
} else {
this.chart_col = new SimpleStringProperty(chrt.toString());
}
this.pane_col = new SimpleStringProperty(pne);
this.on_col = new SimpleBooleanProperty(sel);
this.chrt = chrt;
}
public String getTool() {
return tool_col.get();
}
public void setTool(String tl) {
tool_col.set(tl);
}
public WindowsItem getChart() {
return chrt;
}
public void setChart(WindowsItem _chrt) {
System.out.println("Indicators::setChart "+chrt.toString());
chrt = _chrt;
}
public String getPane() {
return pane_col.get();
}
public void setPane(String pne) {
pane_col.set(pne);
}
public Boolean getOn() {
return on_col.get();
}
public void setOn(boolean sel) {
on_col.set(sel);
}
public SimpleBooleanProperty onProperty() {
return on_col;
}
public SimpleStringProperty toolProperty() {
return tool_col;
}
public SimpleStringProperty chartProperty() {
return chart_col;
}
public SimpleStringProperty paneProperty() {
return pane_col;
}
}
I have a
private TableView<Indicators> tableviewIndicators;
In this column
private TableColumn<Indicators, WindowsItem> tablecolumnFrame;
public static class WindowsItem {
InternalWindow chrt;
private WindowsItem(InternalWindow _chrt) {
chrt = _chrt;
}
public String toString() {
return chrt.getTitle();
}
}
I would like to have a combobox or choicebox where every item type is
WindowsItem
How can I accomplish this?
I have tried this code
tablecolumnFrame.setCellFactory(new Callback<TableColumn<Indicators, WindowsItem>, TableCell<Indicators, WindowsItem>>() {
#Override
public TableCell<Indicators, WindowsItem> call(TableColumn<Indicators, WindowsItem> param) {
TableCell<Indicators, WindowsItem> cell = new TableCell<Indicators, WindowsItem>() {
#Override
public void updateItem(WindowsItem item, boolean empty) {
super.updateItem(item, empty);
if(empty){
return;
}
if (item != null) {
//final ChoiceBox<WindowsItem> choice = new ChoiceBox<>();
final ComboBox<WindowsItem> choice = new ComboBox<>();
int itemsInTab = chartsInTab.getChildren().size();
InternalWindow winItem;
for (int i = 0; i < itemsInTab; i++) {
if (chartsInTab.getChildren().get(i) instanceof InternalWindow) {
winItem = (InternalWindow) chartsInTab.getChildren().get(i);
choice.getItems().add(new WindowsItem(winItem));
//choice.getItems().add(winItem.toString());
System.out.println("winItem.toString() "+winItem.toString());
}
}
But it return this error
SEVERE: javafx.scene.control.Control loadSkinClass Failed to load skin 'StringProperty [bean: TableRow[id=null, styleClass=cell indexed-cell table-row-cell], name: skinClassName, value: com.sun.javafx.scene.control.skin.TableRowSkin]' for control TableRow[id=null, styleClass=cell indexed-cell table-row-cell]
You can try this:
private TableColumn<Indicators, WindowsItem> tablecolumnFrame;
and
public static class Indicators {
private final SimpleStringProperty tool_col;
private final SimpleStringProperty pane_col;
private final SimpleBooleanProperty on_col;
private final SimpleObjectProperty<WindowsItem> chrt;
private Indicators(String tl, WindowsItem chrt, String pne, Boolean sel) {
this.tool_col = new SimpleStringProperty(tl);
this.chrt = new SimpleObjectProperty<>(chrt);
this.pane_col = new SimpleStringProperty(pne);
this.on_col = new SimpleBooleanProperty(sel);
}
public String getTool() {
return tool_col.get();
}
public void setTool(String tl) {
tool_col.set(tl);
}
public WindowsItem getChart(){
return chrt.getValue();
}
public void setChart(WindowsItem _chrt) {
chrt.set(_chrt);
}
public String getPane() {
return pane_col.get();
}
public void setPane(String pne) {
pane_col.set(pne);
}
public Boolean getOn() {
return on_col.get();
}
public void setOn(boolean sel) {
on_col.set(sel);
}
public SimpleBooleanProperty onProperty() {
return on_col;
}
public SimpleStringProperty toolProperty() {
return tool_col;
}
public SimpleObjectProperty<WindowsItem> chartProperty() {
return chrt;
}
public SimpleStringProperty paneProperty() {
return pane_col;
}
}
be careful to:
public SimpleObjectProperty<WindowsItem> chartProperty() {
return chrt;
}
in your previous code was:
public SimpleStringProperty chartProperty() {
return chart_col;
}
this is the reason for the
SEVERE: javafx.scene.control.Control loadSkinClass Failed to load skin 'StringProperty

How to get a WPF datagrid column resize event?

I want to dynamically load and store the Datagrid column widths from my ini file. Write to my inifile for every resize of the column width. Which event can i ues for this. Could any body give any Suggetions or sample code for this.
i use apllicationsettings within a behavior for such things and save the information on application exit.
usage
<DataGrid>
<i:Interaction.Behaviors>
<local:DataGridBehavior GridSettings="{Binding Source={x:Static local:MySettings.Instance},Mode=OneWay}" />
</i:Interaction.Behaviors>
</DataGrid>
settings
[SettingsManageabilityAttribute(SettingsManageability.Roaming)]
public sealed class MySettings: ApplicationSettingsBase, IGridSettings
{
private static readonly Lazy<MySettings> LazyInstance = new Lazy<MySettings>(() => new KadiaSettings());
public static MySettingsInstance { get { return LazyInstance.Value; } }
[UserScopedSettingAttribute()]
[DefaultSettingValue("")]
[SettingsSerializeAs(SettingsSerializeAs.Xml)]
public SerializableDictionary<string, int> GridDisplayIndexList
{
get { return (SerializableDictionary<string, int>)this["GridDisplayIndexList"]; }
set { this["GridDisplayIndexList"] = value; }
}
[UserScopedSettingAttribute()]
[DefaultSettingValue("")]
[SettingsSerializeAs(SettingsSerializeAs.Xml)]
public SerializableDictionary<string, Visibility> GridColumnVisibilityList
{
get { return (SerializableDictionary<string, Visibility>)this["GridColumnVisibilityList"]; }
set { this["GridColumnVisibilityList"] = value; }
}
[UserScopedSettingAttribute()]
[DefaultSettingValue("")]
[SettingsSerializeAs(SettingsSerializeAs.Xml)]
public SerializableDictionary<string, double> GridColumnWidthList
{
get { return (SerializableDictionary<string, double>)this["GridColumnWidthList"]; }
set { this["GridColumnWidthList"] = value; }
}
private MySettings()
{
Application.Current.Exit += OnExit;
}
private void OnExit(object sender, ExitEventArgs e)
{
this.Save();
}
}
public interface IGridSettings: INotifyPropertyChanged
{
SerializableDictionary<string, int> GridDisplayIndexList { get; }
SerializableDictionary<string, Visibility> GridColumnVisibilityList { get; }
SerializableDictionary<string, double> GridColumnWidthList { get; }
}
[XmlRoot("Dictionary")]
public class SerializableDictionary<TKey, TValue>: Dictionary<TKey, TValue>, IXmlSerializable
{
#region IXmlSerializable Members
public System.Xml.Schema.XmlSchema GetSchema()
{
return null;
}
public void ReadXml(System.Xml.XmlReader reader)
{
var keySerializer = new XmlSerializer(typeof(TKey));
var valueSerializer = new XmlSerializer(typeof(TValue));
bool wasEmpty = reader.IsEmptyElement;
reader.Read();
if (wasEmpty)
return;
while (reader.NodeType != System.Xml.XmlNodeType.EndElement)
{
reader.ReadStartElement("item");
reader.ReadStartElement("key");
var key = (TKey)keySerializer.Deserialize(reader);
reader.ReadEndElement();
reader.ReadStartElement("value");
var value = (TValue)valueSerializer.Deserialize(reader);
reader.ReadEndElement();
this.Add(key, value);
reader.ReadEndElement();
reader.MoveToContent();
}
reader.ReadEndElement();
}
public void WriteXml(System.Xml.XmlWriter writer)
{
var keySerializer = new XmlSerializer(typeof(TKey));
var valueSerializer = new XmlSerializer(typeof(TValue));
foreach (TKey key in this.Keys)
{
writer.WriteStartElement("item");
writer.WriteStartElement("key");
keySerializer.Serialize(writer, key);
writer.WriteEndElement();
writer.WriteStartElement("value");
TValue value = this[key];
valueSerializer.Serialize(writer, value);
writer.WriteEndElement();
writer.WriteEndElement();
}
}
#endregion
}
behavior
public class DataGridBehavior : Behavior<DataGrid>
{
public static readonly DependencyProperty GridSettingsProperty =
DependencyProperty.Register("GridSettings", typeof(IGridSettings), typeof(DataGridBehavior), null);
public IGridSettings GridSettings
{
get { return (IGridSettings)GetValue(GridSettingsProperty); }
set { SetValue(GridSettingsProperty, value); }
}
public DataGridICollectionViewSortMerkerBehavior()
{
Application.Current.Exit += CurrentExit;
}
private void CurrentExit(object sender, ExitEventArgs e)
{
SetSettings();
}
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.Loaded += AssociatedObjectLoaded;
AssociatedObject.Unloaded += AssociatedObjectUnloaded;
}
protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.Loaded -= AssociatedObjectLoaded;
AssociatedObject.Unloaded -= AssociatedObjectUnloaded;
}
private void AssociatedObjectUnloaded(object sender, RoutedEventArgs e)
{
SetSettings();
}
void AssociatedObjectLoaded(object sender, RoutedEventArgs e)
{
var settings = GridSettings;
var columns = AssociatedObject.Columns.ToList();
var colCount = columns.Count;
foreach (var column in columns)
{
var key = column.Header.ToString();
if (settings.GridDisplayIndexList.ContainsKey(key))
{
//manchmal wird -1 als index abgespeichert
var index = settings.GridDisplayIndexList[key];
if(index > 0 && index < colCount)
column.DisplayIndex = index;
}
if (settings.GridColumnVisibilityList.ContainsKey(key))
{
column.Visibility = settings.GridColumnVisibilityList[key];
}
if (settings.GridColumnWidthList.ContainsKey(key))
{
column.Width = new DataGridLength(settings.GridColumnWidthList[key]);
}
}
}
private void SetSettings()
{
var settings = GridSettings;
foreach (var column in AssociatedObject.Columns)
{
var key = column.Header.ToString();
var displayindex = column.DisplayIndex;
var visibility = column.Visibility;
var width = column.ActualWidth;
if (settings.GridDisplayIndexList.ContainsKey(key))
{
settings.GridDisplayIndexList[key] = displayindex;
}
else
{
settings.GridDisplayIndexList.Add(key, displayindex);
}
if (settings.GridColumnVisibilityList.ContainsKey(key))
{
settings.GridColumnVisibilityList[key] = visibility;
}
else
{
settings.GridColumnVisibilityList.Add(key, visibility);
}
if (settings.GridColumnWidthList.ContainsKey(key))
{
settings.GridColumnWidthList[key] = width;
}
else
{
settings.GridColumnWidthList.Add(key, width);
}
}
}
}

Calculated Properties using Partial Classes(WPF)

I am trying to use the calculated columns to display in my grid.
I have a partial class automatically generated by EF code generator with three properties:
Here is my code generated by EF entity generator
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Globalization;
using System.Runtime.Serialization;
using System.ComponentModel.DataAnnotations;
namespace Employees.Contract
{
[DataContract(IsReference = true)]
[KnownType(typeof(Department))]
[KnownType(typeof(PropertyType))]
public partial class Employee: IObjectWithChangeTracker, INotifyPropertyChanged,IDataErrorInfo
{
[NonSerialized]
private CLOS.Contract.Validation.DataErrorInfoSupport dataErrorInfoSupport;
public Employee()
{
dataErrorInfoSupport = new CLOS.Contract.Validation.DataErrorInfoSupport(this);
Init();
}
partial void Init();
string IDataErrorInfo.Error { get { return dataErrorInfoSupport.Error; } }
string IDataErrorInfo.this[string memberName] { get { return dataErrorInfoSupport[memberName]; } }
#region Primitive Properties
[DataMember]
public Nullable<decimal> Salary
{
get { return _salary; }
set
{
if (_salary != value)
{
_salary = value;
OnPropertyChanged("Salary");
}
}
}
private Nullable<decimal> _salary;
[DataMember]
public Nullable<decimal> WageRate
{
get { return _wageRate; }
set
{
if (_wageRate != value)
{
_wageRate = value;
OnPropertyChanged("WageRate");
}
}
}
private Nullable<decimal> _wageRate;
[DataMember]
public Nullable<decimal> Bonus
{
get { return _bonus; }
set
{
if (_bonus != value)
{
_bonus = value;
OnPropertyChanged("Bonus");
}
}
}
private Nullable<decimal> _bonus;
#endregion
#region Navigation Properties
[DataMember]
public Department Department
{
get { return _department; }
set
{
if (!ReferenceEquals(_department, value))
{
var previousValue = _department;
_department = value;
OnNavigationPropertyChanged("Department");
}
}
}
private Borrower _department;
[DataMember]
public PropertyType PropertyType
{
get { return _propertyType; }
set
{
if (!ReferenceEquals(_propertyType, value))
{
var previousValue = _propertyType;
_propertyType = value;
OnNavigationPropertyChanged("PropertyType");
}
}
}
private PropertyType _propertyType;
#endregion
#region ChangeTracking
protected virtual void OnPropertyChanged(String propertyName)
{
if (ChangeTracker.State != ObjectState.Added && ChangeTracker.State != ObjectState.Deleted)
{
ChangeTracker.State = ObjectState.Modified;
}
if (_propertyChanged != null)
{
_propertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
protected virtual void OnNavigationPropertyChanged(String propertyName)
{
if (_propertyChanged != null)
{
_propertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged{ add { _propertyChanged += value; } remove { _propertyChanged -= value; } }
private event PropertyChangedEventHandler _propertyChanged;
private ObjectChangeTracker _changeTracker;
[DataMember]
public ObjectChangeTracker ChangeTracker
{
get
{
if (_changeTracker == null)
{
_changeTracker = new ObjectChangeTracker();
_changeTracker.ObjectStateChanging += HandleObjectStateChanging;
}
return _changeTracker;
}
set
{
if(_changeTracker != null)
{
_changeTracker.ObjectStateChanging -= HandleObjectStateChanging;
}
_changeTracker = value;
if(_changeTracker != null)
{
_changeTracker.ObjectStateChanging += HandleObjectStateChanging;
}
}
}
private void HandleObjectStateChanging(object sender, ObjectStateChangingEventArgs e)
{
if (e.NewState == ObjectState.Deleted)
{
ClearNavigationProperties();
}
}
protected bool IsDeserializing { get; private set; }
[OnDeserializing]
public void OnDeserializingMethod(StreamingContext context)
{
IsDeserializing = true;
}
[OnDeserialized]
public void OnDeserializedMethod(StreamingContext context)
{
dataErrorInfoSupport = new CLOS.Contract.Validation.DataErrorInfoSupport(this);
IsDeserializing = false;
ChangeTracker.ChangeTrackingEnabled = true;
}
protected virtual void ClearNavigationProperties()
{
Department = null;
PropertyType = null;
}
#endregion
}
}
It also works if i put OnPropertyChanged("Salary") in Hours,Wage,Overtime Property in EF Generated class (which is not a good idea) because if the class gets regenerated , my code will be wiped out
Any help is appreciated. (Sorry for the formatting , this is my first question)
Thanks
Final Draft
(I removed old edits due to irrelevance)
In your partial class add, in addition to your definition of Salary:
partial void Init()
{
_propertyChanged += NotifySalary;
}
private void NotifySalary(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "Wages" || e.PropertyName == "Hours" || e.PropertyName == "Overtime")
{
OnPropertyChanged("Salary");
}
}
I was able to fix this issue. What was happening is that service was marshaling the data back to the UI but it was not marshaling the events with the properties, so what i had to do was to call the init method from the UI and it started working.

Binding Up Nested UserComponent To it ViewModel

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

WPF and State Machine Pattern

I want to implement functionality that give possibility switch tabItems (TabItem1,TabItem2,TabItem3), when user click button "next" on the Form. And for that reason I'd like to use State Machine Pattern.
These things I've already implemented, but I have no clue, is it right or not?:
public abstract class State
{
#region Constructros
public State()
{
}
public State(State state)
{
this.CurrentState = state.CurrentState;
this.PreviousState = state.PreviousState;
this.NextState = state.NextState;
}
public State(Machine machine,string strCurrentState,string strPreviousState,string strNextState)
{
this.CurrentState = strCurrentState;
this.PreviousState = strPreviousState;
this.NextState = strNextState;
this.SetParams();
}
#endregion
public const string WELCOME = "WELCOME";
public const string EMR_CONFIGURATION = "EMR_CONFIGURATION";
public const string MIGRATION = "MIGRATION";
public const string END_OF_STATES = "END_OF_STATES";
private Machine machine;
private string currentState;
private string previousState;
private string nextState;
private string nameState;
public virtual void SetParams() { }
public virtual void ChangeState(Machine m, State s)
{
m.ChangeState(s);
}
//Get The name of State
public Machine Machine
{
get { return this.machine; }
set { this.machine = value; }
}
//Current State
public string CurrentState
{
get { return this.currentState; }
set { this.currentState = value; }
}
//Previous State
public string PreviousState
{
get { return this.previousState; }
set { this.previousState = value; }
}
//Next State
public string NextState
{
get { return this.nextState; }
set { this.nextState = value; }
}
public string NameState
{
get { return this.nameState; }
set { this.nameState = value; }
}
}
public class Machine
{
public State currentState;
public Machine (string strCurrentState,string strPreviousState,string strNextState)
{
currentState = new WelcomeState(this, strCurrentState, strPreviousState, strNextState);
}
public void ChangeState(State setState)
{
currentState = setState;
}
public void SetCurrentState (string state)
{
currentState.CurrentState = state;
}
}
class Transition
{
public State state;
private static Transition getInstance;
protected Transition(){}
public static Transition GetInstance()
{
if (getInstance == null)
{
getInstance = new Transition();
}
return getInstance;
}
public void Transform(State state)
{
if (state == null)
{
return;
}
// Get the type of state.
string stateType = state.GetType().Name;
// WELCOME TabItem
if (state.CurrentState == State.WELCOME)
{
state.ChangeState(state.Machine, new WelcomeState(state));
}
//EMR_CONFIGURATION TabItem
if (state.CurrentState == State.EMR_CONFIGURATION)
{
state.ChangeState(state.Machine, new EMRConfigurationState(state));
}
//MIGRATION TabItem
if (state.CurrentState == State.EMR_CONFIGURATION)
{
state.ChangeState(state.Machine, new MigrationState(state));
}
}
}
public class WelcomeState : State
{
public WelcomeState(State state) : base(state)
{
}
public WelcomeState (Machine machine, string strCurrentState,string strPreviousState,string strNextState):
base(machine, strCurrentState, strPreviousState, strNextState)
{
}
public override void SetParams()
{
this.CurrentState = State.WELCOME;
this.PreviousState = State.WELCOME;
this.NextState = State.EMR_CONFIGURATION;
}
}
public class EMRConfigurationState : State
{
public EMRConfigurationState(State state) : base(state)
{
}
public EMRConfigurationState(Machine machine, string strCurrentState, string strPreviousState, string strNextState) :
base(machine, strCurrentState, strPreviousState, strNextState)
{
}
public override void SetParams()
{
this.CurrentState = State.EMR_CONFIGURATION;
this.PreviousState = State.WELCOME;
this.NextState = State.MIGRATION;
}
}
public class MigrationState: State
{
public MigrationState(State state) : base(state)
{
}
public MigrationState(Machine machine, string strCurrentState, string strPreviousState, string strNextState) :
base(machine, strCurrentState, strPreviousState, strNextState)
{
}
public override void SetParams()
{
this.CurrentState = State.MIGRATION;
this.PreviousState = State.EMR_CONFIGURATION;
this.NextState = State.END_OF_STATES;
}
}
public partial class Window1 : Window
{
private WizardPresenter wizPresenterWelcome = null;
public List<WizardPresenter> stateList;
public Window1()
{
InitializeComponent();
stateList = new List<WizardPresenter>
{
new WizardPresenter(StatePresenter.WELCOME,
StatePresenter.WELCOME,
StatePresenter.EMR_CONFIGURATION),
new WizardPresenter(StatePresenter.EMR_CONFIGURATION,
StatePresenter.WELCOME,StatePresenter.MIGRATION),
new WizardPresenter(StatePresenter.MIGRATION,
StatePresenter.EMR_CONFIGURATION,
StatePresenter.WELCOME),
};
tabControl.ItemsSource = stateList;
}
private WizardPresenter GetWizardPresenter(string strState)
{
foreach (WizardPresenter presenter in stateList)
{
if (presenter.currentStatePresenter.CurrentStatePresenter == strState)
{
return presenter;
break;
}
}
return null;
}
private void button_Click(object sender, RoutedEventArgs e)
{
if (this.wizPresenterWelcome == null)
{
try
{
{
WizardPresenter wp = (WizardPresenter)tabControl.SelectedItem;
string nextState = wp.currentStatePresenter.NextStatePresenter;
tabControl.SelectedIndex = stateList.IndexOf(GetWizardPresenter(nextState));
}
}
catch (Exception ex)
{
MessageBox.Show("Error:" + ex.Message + "Error");
}
}
}
}
If when you run it works then you've got it right, if when you run it doesn't work then you've got it wrong.
In general:
When you're rephrasing a question, edit the original post and add explanations there.
You can create a context class that holds all the relevant states and the current, previous and next state. Each state can handle each change and decide the next state based on:
Runtime value of Context variables.
The context's previous state.
etc.

Resources