App.xaml Object Reference Not Set To An Instance Of An Object - c#

I recently started getting an error in my App.xaml after installing Blend 4, all my ViewModels now show an error of "Object Reference Not Set To An Instance Of An Object". I uninstalled Blend 4 and the errors went away for a few hours and are now back.
I've checked out every commit I've made till the beginning of the project now and the problem still persists, I am completely baffled. What is going on here? This is causing my windows to throw errors in design mode about being unable to locate resources.
Edit:An Update: Every few times I build the application it changes, this time it changed after changing the binding on a button on a UserControl. Before it was UserListViewModel and SettingViewModel. Now it's SettingsViewModel and MainScreenViewModel.
App.xaml :
<Application x:Class="HelpScoutMetrics.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:HelpScoutMetrics.ViewModel">
<Application.Resources>
<ResourceDictionary>
<vm:MainScreenViewModel x:Key="MainScreenViewModel" />
<vm:SettingsViewModel x:Key="SettingsViewModel" />
<vm:UserListViewModel x:Key="UserListViewModel" />
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Controls.xaml" />
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Fonts.xaml" />
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Colors.xaml" />
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/Blue.xaml" />
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/BaseLight.xaml" />
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/FlatButton.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
ViewModels:
public class MainScreenViewModel : ViewModelBase
{
public MainScreenViewModel()
{
QuickStatistics = new QuickStats();
QuickStatistics.UserQuickStats = new ObservableCollection<UserQuickStat>();
QuickStatistics.UserQuickStats.Add(new UserQuickStat() { Name = "Test", TotalConversations = 93, TotalReplies = 57 });
ApplicationData.MainViewModel = this; // Temp for debug of issues
}
public static Logger logger = LogManager.GetLogger("MainScreenViewModel");
public MainWindow Window { get; set; }
private UserReport m_UserOverall;
public UserReport UserOverall
{
get { return m_UserOverall; }
set { m_UserOverall = value; RaisePropertyChanged("UserOverall"); }
}
private QuickStats m_QuickStatistics;
public QuickStats QuickStatistics
{
get { return m_QuickStatistics; }
set { m_QuickStatistics = value; RaisePropertyChanged("QuickStatistics"); }
}
private DateTime m_SelectedDate;
public DateTime SelectedDate
{
get { return m_SelectedDate; }
set { m_SelectedDate = value; RaisePropertyChanged("SelectedDate"); }
}
private ObservableCollection<DateTime> m_SelectedDates;
public ObservableCollection<DateTime> SelectedDates
{
get { return m_SelectedDates; }
set { m_SelectedDates = value; RaisePropertyChanged("SelectedDates"); }
}
private bool m_EnableLoadQuickStatsButton;
public bool EnableLoadQuickStatsButton
{
get { return m_EnableLoadQuickStatsButton; }
set { m_EnableLoadQuickStatsButton = value; RaisePropertyChanged("EnableLoadQuickStatsButton"); }
}
private bool m_EnableLoadQuickStatsButtonTest = false;
public bool EnableLoadQuickStatsButtonTest
{
get { return m_EnableLoadQuickStatsButtonTest; }
set { m_EnableLoadQuickStatsButtonTest = value; RaisePropertyChanged("EnableLoadQuickStatsButtonTest"); }
}
public void NewUser()
{
QuickStatistics.UserQuickStats.Add(new UserQuickStat() { Name = "Test2", TotalConversations = 953, TotalReplies = 577 });
}
public void OpenSettings()
{
if(Window.SettingsFlyout.IsOpen)
{
Window.SettingsFlyout.IsOpen = false;
logger.Log(LogLevel.Info, "Closed Settings Flyout");
}
else
{
SettingsViewModel viewModel = Window.SettingsFlyout.DataContext as SettingsViewModel;
viewModel.MainWindow = Window;
viewModel.LoadSettings();
Window.SettingsFlyout.IsOpen = true;
logger.Log(LogLevel.Info, "Opened Settings Flyout");
}
}
public void OpenUsersList()
{
if(Window.UserListFlyout.IsOpen)
{
Window.UserListFlyout.IsOpen = false;
logger.Log(LogLevel.Info, "Closed Users List Flyout");
}
else
{
UserListViewModel viewModel = Window.UserListFlyout.DataContext as UserListViewModel;
UserListView userListView = Window.UserListFlyoutView;
viewModel.UserListView = userListView;
viewModel.MainWindow = Window;
viewModel.SetupFreshViewModel();
Window.UserListFlyout.IsOpen = true;
logger.Log(LogLevel.Info, "Opened Users List Flyout");
}
}
public void OpenLogWindow()
{
int count = ApplicationData.MainLogEntries.LogEvents.Count;
NLogViewerView window = new NLogViewerView();
window.Show();
logger.Log(LogLevel.Info, "Opened Log Window");
EnableLoadQuickStatsButtonTest = true;
}
public void RefreshView()// Temp for debug of issues
{
foreach (string name in MiscMethods.GetPropertyNames(this))
{
RaisePropertyChanged(name);
}
}
}
public class SettingsViewModel : ViewModelBase
{
public SettingsViewModel()
{
SettingsWindowLogic.LoadSettings(this);
}
private static Logger logger = LogManager.GetLogger("SettingsViewModel");
public MainWindow MainWindow { get; set; }
private string m_APIKey;
public string APIKey
{
get { return m_APIKey; }
set
{
m_APIKey = value; TriedToValidateKey = false;
KeyValidationButtonText = "Verify Key";
VerifyButtonBackground = new SolidColorBrush(Color.FromArgb(255, 213, 213, 213));
ApplicationData.ApplicationSettings.ValidAPIKeyExists = false;
RaisePropertyChanged("APIKey");
}
}
private bool m_SaveAPIKey = true;
public bool SaveAPIKey
{
get { return m_SaveAPIKey; }
set { m_SaveAPIKey = value; RaisePropertyChanged("SaveAPIKey"); }
}
/*====================================================================
* Key Validation & Button
* ==================================================================*/
private bool m_ValidKey;
public bool ValidKey
{
get { return m_ValidKey; }
set
{
m_ValidKey = value;
if(value)
{
KeyValidationButtonText = "Valid!";
VerifyButtonBackground = new SolidColorBrush(Color.FromArgb(255, 18, 145, 47));
ApplicationData.ApplicationSettings.ValidAPIKeyExists = true;
}
else
{
KeyValidationButtonText = "Invalid";
VerifyButtonBackground = new SolidColorBrush(Color.FromArgb(255, 153, 18, 18));
ApplicationData.ApplicationSettings.ValidAPIKeyExists = false;
}
RaisePropertyChanged("ValidKey");
}
}
//Will be true when the eky is in process of verification
private bool m_CurrentlyVerifyingKey;
public bool CurrentlyVerifyingKey
{
get { return m_CurrentlyVerifyingKey; }
set
{
if (value)
{
KeyValidationButtonText = "Verifying...";
}
m_CurrentlyVerifyingKey = value;
RaisePropertyChanged("CurrentlyVerifyingKey");
}
}
private bool m_TriedToValidateKey;
public bool TriedToValidateKey
{
get { return m_TriedToValidateKey; }
set { m_TriedToValidateKey = value; RaisePropertyChanged("TriedToValidateKey"); }
}
private string m_KeyValidationButtonText = "Verify Key";
public string KeyValidationButtonText
{
get { return m_KeyValidationButtonText; }
set { m_KeyValidationButtonText = value; RaisePropertyChanged("KeyValidationButtonText"); }
}
private Brush m_VerifyButtonBackground = new SolidColorBrush(Color.FromArgb(255, 213, 213, 213));
public Brush VerifyButtonBackground
{
get { return m_VerifyButtonBackground; }
set { m_VerifyButtonBackground = value; RaisePropertyChanged("VerifyButtonBackground"); }
}
public async void VerifyAPIKey()
{
//Task<Paged<Mailbox>> testPull = new Task<Paged<Mailbox>>(() => client.ListMailboxes());
Task<bool> results = new Task<bool>(() => SettingsWindowLogic.VerifyAPIKey(APIKey));
CurrentlyVerifyingKey = true;
results.Start();
CurrentlyVerifyingKey = false;
if (await results)
{
ValidKey = true;
}
else
{
ValidKey = false;
}
TriedToValidateKey = true;
}
public void SaveSettings()
{
SettingsWindowLogic.SaveSettings(this);
logger.Log(LogLevel.Debug, "Saved Settings");
CloseFlyout();
}
public void LoadSettings()
{
SettingsWindowLogic.LoadSettings(this);
}
public void ResetSettings()
{
APIKey = string.Empty;
SaveAPIKey = false;
ApplicationData.ApplicationSettings.ValidAPIKeyExists = false;
logger.Log(LogLevel.Debug, "Reset Settings");
}
public void CloseFlyout()
{
MainWindow.SettingsFlyout.IsOpen = false;
logger.Log(LogLevel.Info, "Closed Settings Flyout");
}
}
public class UserListViewModel : ViewModelBase
{
public UserListViewModel()
{
// LoadUserList();
}
public static Logger logger = LogManager.GetLogger("UserListViewModel");
public MainWindow MainWindow { get; set; }
public UserListView UserListView { get; set; }
private UserList m_UserList;
public UserList UsersList
{
get { return m_UserList; }
set { m_UserList = value; RaisePropertyChanged("UsersList"); }
}
private List<string> m_TestItems;
public List<string> TestItems
{
get { return m_TestItems; }
set { m_TestItems = value; RaisePropertyChanged("TestItems"); }
}
private string m_NewUserName;
public string NewUserName
{
get { return m_NewUserName; }
set { m_NewUserName = value; RaisePropertyChanged("NewUserName"); }
}
private string m_HelpScoutUserListStatus = "Attempting To Load HelpScout Users...";
public string HelpScoutUserListStatus
{
get { return m_HelpScoutUserListStatus; }
set { m_HelpScoutUserListStatus = value; RaisePropertyChanged("HelpScoutUserListStatus"); }
}
private Brush m_HelpScoutUserListStatusColor = new SolidColorBrush(Color.FromArgb(255, 187, 95, 32));
public Brush HelpScoutUserListStatusColor
{
get { return m_HelpScoutUserListStatusColor; }
set { m_HelpScoutUserListStatusColor = value; RaisePropertyChanged("HelpScoutUserListStatusColor"); }
}
private bool m_HelpScoutUserListLoaded;
public bool HelpScoutUserListLoaded
{
get { return m_HelpScoutUserListLoaded; }
set
{
if(value)
{
HelpScoutUserListStatus = UserListWindowLogic.HelpScutUseListStringStatus[0];
HelpScoutUserListStatusColor = UserListWindowLogic.HelpScoutUserListStatusColors[0];
ReverifyUserList();
}
else
{
HelpScoutUserListStatus = UserListWindowLogic.HelpScutUseListStringStatus[1];
HelpScoutUserListStatusColor = UserListWindowLogic.HelpScoutUserListStatusColors[1];
}
m_HelpScoutUserListLoaded = value;
RaisePropertyChanged("HelpScoutUserListLoaded");
}
}
private List<User> m_HelpScoutUsersList;
public List<User> HelpScoutUsersList
{
get { return m_HelpScoutUsersList; }
set { m_HelpScoutUsersList = value; RaisePropertyChanged("HelpScoutUsersList"); }
}
private List<string> m_HelpScoutUsersListStrings = new List<string>();
public List<string> HelpScoutUsersListStrings
{
get { return m_HelpScoutUsersListStrings; }
set { m_HelpScoutUsersListStrings = value; RaisePropertyChanged("HelpScoutUsersListStrings"); }
}
public async void RetrieveHelpScoutUserList()
{
Task<List<User>> task = new Task<List<User>>(() => UserListWindowLogic.RetrieveHelpScoutUserList());
task.Start();
List<User> usersList = await task;
if(usersList != null)
{
HelpScoutUsersList = usersList;
foreach(User userObject in usersList)
{
HelpScoutUsersListStrings.Add(userObject.Name);
}
HelpScoutUserListLoaded = true;
}
else
{
HelpScoutUserListLoaded = false;
}
}
private User MatchUserID(string name)
{
return UserListWindowLogic.FindUserByName(name, HelpScoutUsersList);
}
public void RemoveUser()
{
User user = UserListView.NamesDataGrid.SelectedItem as User;
UsersList.Users.Remove(user);
logger.Log(LogLevel.Debug, "Removed User: " + user.Name);
}
public void AddUser()
{
if (!string.IsNullOrEmpty(NewUserName) && HelpScoutUserListLoaded)
{
User user = MatchUserID(NewUserName);
if(user != null)
{
UsersList.Users.Add(user);
logger.Log(LogLevel.Debug, "Added New Valid User: " + user.Name);
}
else
{
UsersList.Users.Add(new User() { Name = NewUserName });
logger.Log(LogLevel.Debug, "Added New User: " + NewUserName);
}
}
else
{
UsersList.Users.Add(new User() { Name = NewUserName });
logger.Log(LogLevel.Debug, "Added New User: " + NewUserName);
}
ClearNewUserNameTextBox();
}
//Clears the new user textbox
public void ClearNewUserNameTextBox()
{
NewUserName = string.Empty;
}
public void SetupFreshViewModel()
{
m_HelpScoutUserListLoaded = false;
HelpScoutUserListStatusColor = new SolidColorBrush(Color.FromArgb(255, 187, 95, 32));
HelpScoutUserListStatus = "Attempting To Load HelpScout Users...";
LoadUserList();
RetrieveHelpScoutUserList();
}
public void SaveUserList()
{
UserListWindowLogic.SaveUserList(this);
logger.Log(LogLevel.Debug, "Saved Users List");
CloseFlyout();
}
public void ReverifyUserList()
{
UserListWindowLogic.CheckUserListValidity(HelpScoutUsersList);
LoadUserList();
}
public void LoadUserList()
{
UserList userList;
if(ApplicationData.Users != null)
{
userList = XMLSerialize<UserList>.CopyData(ApplicationData.Users);
}
else
{
userList = UserListWindowLogic.CreateNewUserList();
}
UsersList = userList;
}
public void ResetUserList()
{
UsersList = new UserList();
logger.Log(LogLevel.Debug, "Reset Users List");
}
public void CloseFlyout()
{
MainWindow.UserListFlyout.IsOpen = false;
logger.Log(LogLevel.Info, "Closed Users List Flyout");
}
}
public class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged(String propertyName)
{
PropertyChangedEventHandler temp = PropertyChanged;
if (temp != null)
{
temp(this, new PropertyChangedEventArgs(propertyName));
}
}
public bool IsInDesignMode
{
get
{
var prop = DesignerProperties.IsInDesignModeProperty;
return (bool)DependencyPropertyDescriptor
.FromProperty(prop, typeof(FrameworkElement))
.Metadata.DefaultValue;
}
}
}

You need to make sure that the constructor of your view model can be initialized in design time, if you're using some dependencies in the constructor that cannot be initialized in design time, you need to put it inside the condition block: if(!IsInDesignMode)

Related

Layout.RaiseChild(View) Method in Xamarin.Forms

RelativeLayout :
How Can we write Layout.RaiseChild(View) Method in XAML?
( or )
How can we write in ViewModel?
namespace MatchesProject.ViewModels
{
public class MatchesViewModel : BindableObject
{
private int _lastItemAppearedIdx = 0;
private bool IsLastDirectionWasUp = false;
private bool stackMatchTypesIsVisible { get; set; }
public bool StackMatchTypesIsVisible
{
get => stackMatchTypesIsVisible;
set
{
if (value == stackMatchTypesIsVisible)
return;
stackMatchTypesIsVisible = value;
OnPropertyChanged();
}
}
public ObservableCollection<MatchProfile> MatchesList { get; set; }
public ICommand ItemDisappearingCommand
{
get;
private set;
}
private void ItemDisappearing(object obj)
{
try
{
MatchProfile profile = obj as MatchProfile;
if (MatchesList != null && MatchesList.Contains(profile))
{
if (MatchesList.Contains(profile))
{
var currentIdx = MatchesList.IndexOf(profile);
if (currentIdx > _lastItemAppearedIdx)
{
StackMatchTypesIsVisible = false;
IsLastDirectionWasUp = true;
}
else if (IsLastDirectionWasUp)
{
IsLastDirectionWasUp = false;
StackMatchTypesIsVisible = true;
MessagingCenter.Send(this, "RaiseChild", "");
}
_lastItemAppearedIdx = currentIdx;
}
}
}
catch (Exception) { }
}
public MatchesViewModel()
{
ItemDisappearingCommand = new Command(ItemDisappearing);
MatchesList = new ObservableCollection<MatchProfile>();
BindingContext = MatchesList;
}
}
}
//MatchesPage.xaml.cs
public partial class MatchesPage : ContentPage
{
public MatchesPage()
{
InitializeComponent();
MessagingCenter.Subscribe<MatchesPageViewModel>(this, "RaiseChild", (page) => { relativeCompletePage.RaiseChild(stackMatchTypes); });
}
}
I am using RelativeLayout and inside this more than 2 stack layouts with one Listview. While Scrolling listview, Some cases I need to bring front the StackLayout. That's why I have used MessageCenter. I need to know, Is there have any other better option to fix?

I want to update a property in my primaryviewmodel from the viewmodel that I use in my usercontrol

I am trying to update my treeview in primary viewmodel everytime I add an object to my database in my usercontrol viewmodel.
This is the code in my primary viewmodel
public class RechtbankenRechtersViewModel : Basis
{
IUnitOfWork uow = new UnitOfWork(new RechtContext());
private ObservableCollection<Rechtbank> _rechtbanken;
private IntroRechtbankenEnRechters intro = new IntroRechtbankenEnRechters();
private UserControl _control;
private ObservableCollection<TreeViewItem> _tree;
private TreeViewItem _treeItem;
public TreeViewItem TreeItem
{
get
{
return _treeItem;
}
set
{
_treeItem = value;
NotifyPropertyChanged();
}
}
public string Title { get; set; }
public UserControl Control
{
get
{
return _control;
}
set
{
_control = value;
NotifyPropertyChanged();
}
}
public ObservableCollection<TreeViewItem> Tree
{
get
{
return _tree;
}
set
{
_tree = value;
NotifyPropertyChanged();
}
}
public ObservableCollection<Rechtbank> Rechtbanken
{
get
{
return _rechtbanken;
}
set
{
_rechtbanken = value;
BouwBoom();
NotifyPropertyChanged();
}
}
public override string this[string columnName] => throw new NotImplementedException();
public RechtbankenRechtersViewModel()
{
Title = "Rechtbanken en rechters";
Tree = new ObservableCollection<TreeViewItem>();
TreeItem = new TreeViewItem();
Rechtbanken = new ObservableCollection<Rechtbank>(uow.RechtbankRepo.Ophalen(x => x.Rechters));
IntroRechtbankenEnRechters intro = new IntroRechtbankenEnRechters();
Control = intro;
}
//gaat de lijst van Tree opvullen met treeviewitems
public void BouwBoom()
{
foreach (var rechtbank in Rechtbanken)
{
TreeViewItem parent = new TreeViewItem() { Header = rechtbank.Naam, Tag = rechtbank.RechtbankID, Name="Rechtbank"};
foreach (var rechter in rechtbank.Rechters)
{
parent.Items.Add(new TreeViewItem() { Header = "Rechter - " + rechter.Voornaam + " " + rechter.Achternaam, Tag = rechter.RechterID, Name = "Rechter" });
}
Tree.Add(parent);
}
}
The Method BouwBoom is what fills my treeview since I struggled with it in the xaml(not much of a designer)
when opening the usercontrol i pass through the tag so that i can load the correct data into an object
my usercontrol viewmodel looks like this
public class OperatiesRechterViewModel : Basis
{
private RechtersRechtbanken context = (RechtersRechtbanken)Application.Current.Windows[1];
private Rechtbank _selectedRechtbank;
private ObservableCollection<Rechtbank> _rechtbanken;
private Rechter _rechter;
IUnitOfWork uow = new UnitOfWork(new RechtContext());
public override string this[string columnName] => throw new NotImplementedException();
public Rechter Rechter
{
get
{
return _rechter;
}
set
{
_rechter = value;
NotifyPropertyChanged();
}
}
public Rechtbank SelectedRechtbank
{
get
{
return _selectedRechtbank;
}
set
{
_selectedRechtbank = value;
NotifyPropertyChanged();
}
}
public ObservableCollection<Rechtbank> Rechtbanken
{
get
{
return _rechtbanken;
}
set
{
_rechtbanken = value;
}
}
public OperatiesRechterViewModel()
{
Rechter = new Rechter();
Rechtbanken = new ObservableCollection<Rechtbank>(uow.RechtbankRepo.Ophalen());
}
public OperatiesRechterViewModel(int id)
{
Rechter = uow.RechterRepo.ZoekOpPK(id);
Rechtbanken = new ObservableCollection<Rechtbank>(uow.RechtbankRepo.Ophalen());
SelectedRechtbank = uow.RechtbankRepo.Ophalen(x => x.RechtbankID == Rechter.RechtbankID).SingleOrDefault();
}
public override bool CanExecute(object parameter)
{
switch (parameter.ToString())
{
case "Toevoegen":
if (Rechter.RechterID <= 0)
{
return true;
}
return false;
case "Wijzigen":
if (Rechter.RechterID > 0)
{
return true;
}
return false;
case "Verwijderen":
if (Rechter.RechterID > 0)
{
return true;
}
return false;
}
return false;
}
public string FoutmeldingInstellen()
{
string melding = "";
if (SelectedRechtbank == null)
{
}
return melding;
}
public void Toevoegen()
{
if (SelectedRechtbank != null)
{
Rechter.RechtbankID = SelectedRechtbank.RechtbankID;
if (Rechter.Voornaam != "")
{
if (Rechter.Achternaam != "")
{
uow.RechterRepo.Toevoegen(Rechter);
int ok = uow.Save();
if (ok > 0)
{
MessageBox.Show("Rechter is toegevoegd!");
///refresh view in principe
context.DataContext = new RechtbankenRechtersViewModel();
}
}
else
{
//
}
}
else
{
//foutmelding maken
}
}
else
{
//foutmelding maken
}
}
public override void Execute(object parameter)
{
switch (parameter.ToString())
{
case "Toevoegen":
Toevoegen();
break;
}
}
}
}
As you can see here, I use the application.current.windows method to get the activated window and then I update it's datacontext when toevoegen(add) is pressed.
However I don't know if this is allowed in mvvm.
Can somebody help me?
Solved it!
for those who want to do the same thing just pass on the function to the constructor of the usercontrol viewmodel as an action then inside the uc viewmodel you can invoke it

How to disable button when the login is false using MVVM,WPF in C#

I am studying the mvvm pattern and ran into a problem, I need to make sure that the button is inactive when the user entered his data incorrectly
I have dialog window (loginPage) where i vote Login and Password
public class LoginViewModel : ViewModel
{
ApplicationDbContext db;
IEnumerable<User> users;
IAuthorizationService _authorizationService;
IHashingManager _hashingManager;
private bool? _closeWindow;
private RelayCommand _loginUser;
private RelayCommand _cancelCommand;
public bool EnableClose { get; set; }
public LoginViewModel(IViewFactory viewFactory, ICore core) : base(viewFactory)
{
_authorizationService = core.AuthorizationService;
_hashingManager = core.HashingManager;
db = new ApplicationDbContext();
}
public ICommand Command { get; set; }
private string login;
public string Login
{
get => login;
set
{
login = value;
RaisePropertyChanged(nameof(Login));
}
}
private string password;
public string Password
{
get => password;
set
{
password = value;
RaisePropertyChanged(nameof(Password));
}
}
public RelayCommand CancelCommand
{
get
{
return _cancelCommand ??
(_cancelCommand = new RelayCommand(() =>
{
var result = _authorizationService.Login(Login, _hashingManager.Encrypt(Password));
CloseWindow = true;
}));
}
}
public bool? CloseWindow
{
get { return _closeWindow; }
set
{
_closeWindow = value;
RaisePropertyChanged(nameof(CloseWindow));
}
}
public RelayCommand LoginUser
{
get
{
return _loginUser ??
(_loginUser = new RelayCommand(() =>
{
var result = _authorizationService.Login(Login, _hashingManager.Encrypt(Password));
CloseWindow = true;
}));
}
}
public IEnumerable<User> Users
{
get { return users; }
set
{
users = value;
RaisePropertyChanged("Users");
}
}
}
My MainWindow VM
public class MainViewModel : ViewModel
{
private readonly ICore _core;
public ICommand LoginCommand { get; }
public ObservableCollection<ILayoutElementViewModel> Documents { get; private set; }
public MainViewModel(IViewFactory viewFactory, ICore core) : base(viewFactory)
{
_core = core;
this.Documents = new ObservableCollection<ILayoutElementViewModel>();
}
ServiceResult _serviceResult = new ServiceResult();
private RelayCommand openChartView;
public RelayCommand OpenChartView
{
get
{
return openChartView ??
(openChartView = new RelayCommand(()=>
{
if (_serviceResult.IsSucceed)
{
var chartView = new ChartSelectionViewModel(_viewFactory);
_viewFactory.ShowDialogView(chartView);
}
}));
}
}
private string _myProperty;
public string MyProperty
{
get => _myProperty;
set
{
_myProperty = value;
RaisePropertyChanged(() => MyProperty);
}
}
protected override void LoadedExecute()
{
base.LoadedExecute();
_viewFactory.ShowDialogView(new LoginViewModel(_viewFactory, _core));
}
}
When i wrote corectly or not, my dialog window close and main window becomes active.
There is a button , and i want disable this button when the login and password was incorrect.
I think i must use my ServiceResult in MW
public class ServiceResult
{
public bool IsSucceed { get; set; }
public string Error { get; set; }
public ServiceResult()
{
IsSucceed = true;
}
public ServiceResult(string error)
{
IsSucceed = false;
Error = error;
}
}
or
AuthorizationService
public class AuthorizationService : IAuthorizationService
{
public ServiceResult Login(string login,string password)
{
ApplicationDbContext db = new ApplicationDbContext();
var listUsers = db.Users.ToList();
foreach (var item in listUsers)
{
if (item.Login == login && item.Password == password)
{
return new ServiceResult();
}
}
return new ServiceResult("Wrong Login or Password!");
}
}
How can i do that? Thx u.
I done, it was so easy
protected override void LoadedExecute()
{
base.LoadedExecute();
var vm = new LoginViewModel(_viewFactory, _core);
_viewFactory.ShowDialogView(vm);
IsAuth = vm.AuthorizationResult;
}
private RelayCommand openChartView;
public RelayCommand OpenChartView
{
get
{
return openChartView ??
(openChartView = new RelayCommand(()=>
{
if (IsAuth)
{
var chartView = new ChartSelectionViewModel(_viewFactory);
_viewFactory.ShowDialogView(chartView);
}
}));
}
}
You can do a bool binding to the IsEnable property of the button.
code:
public bool Enabled
{
get => _enabled; set
{
_enabled = value;
NotifypropertyChanged("Enabled");
}
}
xaml:
<Button IsEnabled="{Binding Enabled}"></Button>

ObservableCollection that fires when containing items change

I found this topic to be a real struggle for a lot of people here and it therefore is actually covered pretty good! Nevertheless, none of the provided solutions seems to work for me.
As the title says, its about the problem that ObservableCollection doesnt fire when the value of the item changes, only if the Item itself gets removed, added or changed in some way.
I tried solutions with BindingList- even though a lot of people disadvice it - and it didnt work, solutions with extended ObservableCollections like it is explained here. None of it seems to work...which leaves the question whether the error is where i think it is or somewhere completely else!!
Alright heres my code:
BaseClasses:
public class ModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propName = "")
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}
}
class TestSensor : ModelBase
{
private bool isOnline;
public bool IsOnline
{
get
{
return isOnline;
}
set
{
if (isOnline != value)
{
isOnline = value;
this.OnPropertyChanged();
}
}
}
private double sensorDatauStrain;
public double SensorDatauStrain
{
get { return sensorDatauStrain; }
set
{
if (sensorDatauStrain != value)
{
sensorDatauStrain = value;
this.OnPropertyChanged();
}
}
}
private double sensorDatakNewton;
public double SensorDatakNewton
{
get { return sensorDatakNewton; }
set
{
if (sensorDatakNewton != value)
{
sensorDatakNewton = value;
this.OnPropertyChanged();
}
}
}
private double sensorDataTon;
public double SensorDataTon
{
get { return sensorDataTon; }
set
{
if (sensorDataTon != value)
{
sensorDataTon = value;
this.OnPropertyChanged();
}
}
}
private double sensorDatausTon;
public double SensorDatausTon
{
get { return sensorDatausTon; }
set
{
if (sensorDatausTon != value)
{
sensorDatausTon = value;
this.OnPropertyChanged();
}
}
}
private string sensorName;
public string SensorName
{
get { return sensorName; }
set
{
if (sensorName != value)
{
sensorName = value;
this.OnPropertyChanged();
}
}
}
public TestSensor(string name, double ustrain,double kNewton, double ton, double uston)
{
this.SensorName = name;
this.SensorDatauStrain = ustrain;
this.SensorDatakNewton = kNewton;
this.SensorDataTon = ton;
this.SensorDatausTon = uston;
this.IsOnline = true;
}
}
Then i have a class containing these Sensors:
class Holm : ModelBase
{
public Holm(String Name, TestSensor sensor1, TestSensor sensor2)
{
Sensor1 = sensor1;
Sensor2 = sensor2;
this.Name = Name;
}
private string name;
public string Name
{
get
{
return name;
}
set
{
if (name != value)
{
name = value;
this.OnPropertyChanged();
}
}
}
private TestSensor sensor1;
public TestSensor Sensor1
{
get
{
return sensor1;
}
set
{
if (sensor1 != value)
{
sensor1 = value;
this.OnPropertyChanged();
}
}
}
private TestSensor sensor2;
public TestSensor Sensor2
{
get
{
return sensor2;
}
set
{
if (sensor2 != value)
{
sensor2 = value;
this.OnPropertyChanged();
}
}
}
public bool IsOnline
{
get
{
if (!Sensor1.IsOnline || !Sensor2.IsOnline)
{
return false;
}
else
{
return true;
}
}
}
}
And finally the ViewModel that contains my failing ObservableCollection - excluding some things that are not relevant:
class MainViewViewModel : ModelBase
{
public ItemsChangeObservableCollection<Holm> HolmList { get;set;}
public MainViewViewModel()
{
Sensor11 = new TestSensor("Sensor 1.1", 0, 0, 0, 0);
Sensor12 = new TestSensor("Sensor 1.2", 0, 0, 0, 0);
Sensor21 = new TestSensor("Sensor 2.1", 0, 0, 0, 0);
Sensor22 = new TestSensor("Sensor 2.2", 0, 0, 0, 0);
Sensor31 = new TestSensor("Sensor 3.1", 0, 0, 0, 0);
Sensor32 = new TestSensor("Sensor 3.2", 0, 0, 0, 0);
Sensor41 = new TestSensor("Sensor 4.1", 0, 0, 0, 0);
Sensor42 = new TestSensor("Sensor 4.2", 0, 0, 0, 0);
Holm1 = new Holm("Holm 1", Sensor11, Sensor12);
Holm2 = new Holm("Holm 2", Sensor21, Sensor22);
Holm3 = new Holm("Holm 3", Sensor31, Sensor32);
Holm4 = new Holm("Holm 4", Sensor41, Sensor42);
HolmList = new ItemsChangeObservableCollection<Holm>();
HolmList.Add(Holm1);
HolmList.Add(Holm2);
HolmList.Add(Holm3);
HolmList.Add(Holm4);
}
private TestSensor sensor11;
public TestSensor Sensor11
{
get { return sensor11; }
set
{
if (sensor11 != value)
{
sensor11 = value;
this.OnPropertyChanged();
this.OnPropertyChanged("Holm1");
this.OnPropertyChanged("HolmList");
}
}
}
private TestSensor sensor12;
public TestSensor Sensor12
{
get { return sensor12; }
set
{
if (sensor12 != value)
{
sensor12 = value;
this.OnPropertyChanged();
this.OnPropertyChanged("Holm1");
this.OnPropertyChanged("HolmList");
}
}
}
private TestSensor sensor21;
public TestSensor Sensor21
{
get { return sensor21; }
set
{
if (sensor21 != value)
{
sensor21 = value;
this.OnPropertyChanged();
}
}
}
private TestSensor sensor22;
public TestSensor Sensor22
{
get { return sensor22; }
set
{
if (sensor22 != value)
{
sensor22 = value;
this.OnPropertyChanged();
}
}
}
private TestSensor sensor31;
public TestSensor Sensor31
{
get { return sensor31; }
set
{
if (sensor31 != value)
{
sensor31 = value;
this.OnPropertyChanged();
}
}
}
private TestSensor sensor32;
public TestSensor Sensor32
{
get { return sensor32; }
set
{
if (sensor32 != value)
{
sensor32 = value;
this.OnPropertyChanged();
}
}
}
private TestSensor sensor41;
public TestSensor Sensor41
{
get { return sensor41; }
set
{
if (sensor41 != value)
{
sensor41 = value;
this.OnPropertyChanged();
}
}
}
private TestSensor sensor42;
public TestSensor Sensor42
{
get { return sensor42; }
set
{
if (sensor42 != value)
{
sensor42 = value;
this.OnPropertyChanged();
}
}
}
private Holm holm1;
public Holm Holm1
{
get
{
return holm1;
}
set
{
if (holm1 != value)
{
holm1 = value;
this.OnPropertyChanged();
this.OnPropertyChanged("HolmList");
}
}
}
private Holm holm2;
public Holm Holm2
{
get
{
return holm2;
}
set
{
if (holm2 != value)
{
holm2 = value;
this.OnPropertyChanged();
}
}
}
private Holm holm3;
public Holm Holm3
{
get
{
return holm3;
}
set
{
if (holm3 != value)
{
holm3 = value;
this.OnPropertyChanged();
}
}
}
private Holm holm4;
public Holm Holm4
{
get
{
return holm4;
}
set
{
if (holm4 != value)
{
holm4 = value;
this.OnPropertyChanged();
}
}
}
}
The Xaml isnt really important and is not yet finished. I have solved it so far with this code:
<CheckBox Content="Sensor1.1" IsChecked="{Binding HolmList[0].Sensor1.IsOnline}"/>
<TextBlock Text="{Binding HolmList[0].Sensor1.IsOnline, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>
<CheckBox Content="Sensor1.2" IsChecked="{Binding HolmList[0].Sensor2.IsOnline}"/>
<TextBlock Text="{Binding HolmList[0].Sensor2.IsOnline, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>
<TextBlock Text="{Binding HolmList[0].IsOnline, UpdateSourceTrigger=PropertyChanged}" />
All i want is the Holms IsOnline-Property to change to false as soon as one of the Sensors IsOnline-Property changes to false...but it just wouldnt!
In know this is a lot of code, but im actually not sure where the error is located.
Also: It seems to me that my classed have redundant calls to OnPropertyChange()...but im not sure bout it.
Im really thankful for all kind of help on this!!!
Your TextBlock that bound to HolmList[0].IsOnline didn't update because IsOnline on Holm didn't notify that its value changed.
You can listen to TestSensor's PropertyChanged event in TestSensor and notify IsOnline property change when one of TestSensor's IsOnline property change.
class Holm : ModelBase
{
public Holm(String Name, TestSensor sensor1, TestSensor sensor2)
{
Sensor1 = sensor1;
Sensor2 = sensor2;
this.Name = Name;
Sensor1.PropertyChanged += OnSensorOnlineChanged;
Sensor2.PropertyChanged += OnSensorOnlineChanged;
}
private void OnSensorOnlineChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOnline")
{
OnPropertyChanged(nameof(IsOnline));
}
}
}
The nameof keyword
you mean something like this?
public class EnhancedObservableCollection<T> : ObservableCollection<T>
where T : INotifyPropertyChanged
{
public EnhancedObservableCollection(bool isCollectionChangedOnChildChange)
{
IsCollectionChangedOnChildChange = isCollectionChangedOnChildChange;
}
public EnhancedObservableCollection(List<T> list, bool isCollectionChangedOnChildChange) : base(list)
{
IsCollectionChangedOnChildChange = isCollectionChangedOnChildChange;
}
public EnhancedObservableCollection(IEnumerable<T> collection, bool isCollectionChangedOnChildChange) : base(collection)
{
IsCollectionChangedOnChildChange = isCollectionChangedOnChildChange;
}
public bool IsCollectionChangedOnChildChange { get; set; }
public event EventHandler<string> ChildChanged;
protected override void RemoveItem(int index)
{
var item = Items[index];
item.PropertyChanged -= ItemOnPropertyChanged;
base.RemoveItem(index);
}
private void ItemOnPropertyChanged(object sender, PropertyChangedEventArgs propertyChangedEventArgs)
{
var handler = ChildChanged;
if (handler != null)
{
handler(this, propertyChangedEventArgs.PropertyName);
}
if (IsCollectionChangedOnChildChange)
{
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace));
}
}
protected override void InsertItem(int index, T item)
{
base.InsertItem(index, item);
item.PropertyChanged += ItemOnPropertyChanged;
}
}

On Property change took too much time and finally crash application

I am working on WPF MVVM Application.
I have a view (Employee) shown inside Main Region
this view (Employee) contain scoped regions within it where I show/display Employee details views. Its working fine till this place New, display update and delete
But I am facing strange problem with New Operation
If I create view for first time and click on new , Object got initialized my Data Object CurrentEmployee.
But If I load some previous data its been shown properly and then I click on New, my Data Object CurrentEmployee took too much time and finaly crash. the problem so far traced is in OnPropertyChange
Thanks any sort of help/suggestion is highly appriciated
whole code of view model
[Export(typeof(ITB_EMPLOYEEViewModel))]
public class TB_EMPLOYEEViewModel : ViewModelBase, ITB_EMPLOYEEViewModel
{
private TB_EMPLOYEE _currentTB_EMPLOYEE;
IRegionManager RefRegionManager;
IEventAggregator _eventAggregator;
[ImportingConstructor]
public TB_EMPLOYEEViewModel(IRegionManager regionManager, IEventAggregator eventAggregator)
: base(regionManager, eventAggregator)
{
RefRegionManager = regionManager;
HeaderInfo = "TB_EMPLOYEE";
_eventAggregator = eventAggregator;
OpenImageDialog = new DelegateCommand(OpenDialog, CanOpenDialog);
//CurrentTB_EMPLOYEE = new TB_EMPLOYEE();
//empHistoryVM = new TB_EMPLOYEE_HISTORYViewModel();
//UnLoadChild();
//LoadChild();
New();
}
private void LoadChild()
{
IRegionManager regionManager = ServiceLocator.Current.GetInstance<IRegionManager>();
if (regionManager.Regions.ContainsRegionWithName(RegionNames.EmployeeDetail))
{
IRegion region = regionManager.Regions[RegionNames.EmployeeDetail];
var empHistory = ServiceLocator.Current.GetInstance<uTB_EMPLOYEE_HISTORYView>();
if (region.GetView("EmployeeHistory") == null)// .Views.OfType<uTB_EMPLOYEE_HISTORYView>().SingleOrDefault() == null)
{
region.Add(empHistory, "EmployeeHistory");
}
if (CurrentTB_EMPLOYEE != null && CurrentTB_EMPLOYEE.ID!=0)
{
empHistoryVM = new TB_EMPLOYEE_HISTORYViewModel(CurrentTB_EMPLOYEE.ID);
}
else
{
empHistoryVM = new TB_EMPLOYEE_HISTORYViewModel();
}
empHistory.ViewModel = empHistoryVM;
region.Activate(region.GetView("EmployeeHistory"));
}
}
private void UnLoadChild()
{
IRegionManager regionManager = ServiceLocator.Current.GetInstance<IRegionManager>();
if (regionManager.Regions.ContainsRegionWithName(RegionNames.EmployeeDetail))
{
IRegion region = regionManager.Regions[RegionNames.EmployeeDetail];
if (region.GetView("EmployeeHistory") != null)// .Views.OfType<uTB_EMPLOYEE_HISTORYView>().SingleOrDefault() == null)
{
region.Remove(region.GetView("EmployeeHistory"));
}
}
}
#region DetailUserControls ViewModels
private TB_EMPLOYEE_HISTORYViewModel empHistoryVM;
#endregion DetailUserControls ViewModels
#region Commands
public DelegateCommand OpenImageDialog { get; set; }
private bool CanOpenDialog() { return true; }
public void OpenDialog()
{
using (OpenFileDialog objOpenFile = new OpenFileDialog())
{
if (objOpenFile.ShowDialog() == DialogResult.OK)
{
_currentTB_EMPLOYEE.PHOTO = Utility.ConvertImageToByte(objOpenFile.FileName);
CurrentEmployeeImage = Utility.ConvertByteToImage(_currentTB_EMPLOYEE.PHOTO);
}
}
}
public override void ShowSelectedRow()
{
if (RefRegionManager.Regions[RegionNames.MainRegion].Views.OfType<uTB_EMPLOYEEView>().SingleOrDefault() == null)
{
RefRegionManager.RegisterViewWithRegion(RegionNames.MainRegion, typeof(uTB_EMPLOYEEView));
}
RefRegionManager.RequestNavigate(RegionNames.MainRegion, "uTB_EMPLOYEEView");
UnLoadChild();
LoadChild();
}
public override void RegisterCommands()
{
if (RefRegionManager.Regions[RegionNames.MainRegion].ActiveViews.OfType<uTB_EMPLOYEEView>().FirstOrDefault() != null)
{
if (RefRegionManager.Regions[RegionNames.MainRegion].ActiveViews.OfType<uTB_EMPLOYEEView>().FirstOrDefault().ToString() == "WPFApp.View.uTB_EMPLOYEEView")
{
GlobalCommands.ShowAllCommand.RegisterCommand(ShowAllCommand);
GlobalCommands.SaveCommand.RegisterCommand(SaveCommand);
GlobalCommands.NewCommand.RegisterCommand(NewCommand);
GlobalCommands.DeleteCommand.RegisterCommand(DeleteCommand);
GlobalCommands.CloseCommand.RegisterCommand(CloseCommand);
}
}
if (RefRegionManager.Regions[RegionNames.MainRegion].ActiveViews.OfType<uListTB_EMPLOYEE>().FirstOrDefault() != null)
{
if (RefRegionManager.Regions[RegionNames.MainRegion].ActiveViews.OfType<uListTB_EMPLOYEE>().FirstOrDefault().ToString() == "WPFApp.ListView.uListTB_EMPLOYEE")
{
GlobalCommands.CloseCommand.RegisterCommand(CloseCommand);
GlobalCommands.SearchCommand.RegisterCommand(SearchCommand);
GlobalCommands.PrintCommand.RegisterCommand(PrintCommand);
GlobalCommands.ExportToExcelCommand.RegisterCommand(ExportToExcelCommand);
GlobalCommands.ExportToWordCommand.RegisterCommand(ExportToWordCommand);
GlobalCommands.ExportToPDFCommand.RegisterCommand(ExportToPDFCommand);
}
}
}
public override bool CanShowAll()
{
return IsActive;
}
public override void ShowAll()
{
HeaderInfo = "TB_EMPLOYEE List";
if (RefRegionManager.Regions[RegionNames.MainRegion].Views.OfType<uListTB_EMPLOYEE>().SingleOrDefault() == null)
{
RefRegionManager.RegisterViewWithRegion(RegionNames.MainRegion, typeof(uListTB_EMPLOYEE));
}
RefRegionManager.RequestNavigate(RegionNames.MainRegion, "uListTB_EMPLOYEE");
UpdateListFromDB();
}
public override void UpdateListFromDB()
{
using (DBMain objDBMain = new DBMain())
{
TB_EMPLOYEEList = objDBMain.EntTB_EMPLOYEE.ToList<TB_EMPLOYEE>();
}
}
public override void New()
{
this.CurrentTB_EMPLOYEE = new TB_EMPLOYEE();
UnLoadChild();
LoadChild();
}
public override void Close()
{
if (RefRegionManager.Regions[RegionNames.MainRegion].ActiveViews.OfType<uTB_EMPLOYEEView>().FirstOrDefault() != null)
{
if (RefRegionManager.Regions[RegionNames.MainRegion].ActiveViews.OfType<uTB_EMPLOYEEView>().FirstOrDefault().ToString() == "WPFApp.View.uTB_EMPLOYEEView")
{
RefRegionManager.Regions[RegionNames.MainRegion].Remove(RefRegionManager.Regions[RegionNames.MainRegion].ActiveViews.OfType<uTB_EMPLOYEEView>().FirstOrDefault());
UnLoadChild();
}
}
if (RefRegionManager.Regions[RegionNames.MainRegion].ActiveViews.OfType<uListTB_EMPLOYEE>().FirstOrDefault() != null)
{
if (RefRegionManager.Regions[RegionNames.MainRegion].ActiveViews.OfType<uListTB_EMPLOYEE>().FirstOrDefault().ToString() == "WPFApp.ListView.uListTB_EMPLOYEE")
{
RefRegionManager.Regions[RegionNames.MainRegion].Remove(RefRegionManager.Regions[RegionNames.MainRegion].ActiveViews.OfType<uListTB_EMPLOYEE>().FirstOrDefault());
}
}
}
public override void Delete()
{
if (RefRegionManager.Regions[RegionNames.MainRegion].ActiveViews.OfType<uTB_EMPLOYEEView>().FirstOrDefault() != null ||
RefRegionManager.Regions[RegionNames.MainRegion].ActiveViews.OfType<uListTB_EMPLOYEE>().FirstOrDefault() != null)
{
if (CurrentTB_EMPLOYEE != null)
{
ConfirmationDialog confirmationMessage = new ConfirmationDialog("Do You want to Delete this Record of [TB_EMPLOYEE]", "Confirmation Dialog Box");
confirmationMessage.AllowsTransparency = true;
DoubleAnimation animFadeIn = new DoubleAnimation();
animFadeIn.From = 0;
animFadeIn.To = 1;
animFadeIn.Duration = new Duration(TimeSpan.FromSeconds(1));
confirmationMessage.BeginAnimation(Window.OpacityProperty, animFadeIn);
confirmationMessage.ShowDialog();
if (confirmationMessage.DialogValue)
{
if (CurrentTB_EMPLOYEE.ID != 0)
{
using (DBMain objDBMain = new DBMain())
{
objDBMain.Entry<TB_EMPLOYEE>(CurrentTB_EMPLOYEE).State = EntityState.Deleted;
objDBMain.SaveChanges();
OnPropertyChanged("CurrentTB_EMPLOYEE");
CurrentTB_EMPLOYEE = null;
}
}
else
{
CurrentTB_EMPLOYEE = null;
}
UpdateListFromDB();
}
}
}
}
public override bool CanSave()
{
return IsActive;
}
public override void Save()
{
if (RefRegionManager.Regions[RegionNames.MainRegion].ActiveViews.OfType<uTB_EMPLOYEEView>().FirstOrDefault() != null ||
RefRegionManager.Regions[RegionNames.MainRegion].ActiveViews.OfType<uListTB_EMPLOYEE>().FirstOrDefault() != null)
{
if (CurrentTB_EMPLOYEE != null)
{
using (DBMain objDBMain = new DBMain())
{
objDBMain.Entry<TB_EMPLOYEE>(CurrentTB_EMPLOYEE).State = CurrentTB_EMPLOYEE.ID == 0 ? EntityState.Added : EntityState.Modified;
foreach (TB_EMPLOYEE_HISTORY obj in empHistoryVM.TB_EMPLOYEE_HISTORYList)
{
objDBMain.Entry<TB_EMPLOYEE_HISTORY>(obj).State = EntityState.Added;
CurrentTB_EMPLOYEE.TB_EMPLOYEE_HISTORYList.Add(obj);
objDBMain.SaveChanges();
}
}
UpdateListFromDB();
}
}
}
#endregion Commands
#region Properties
private ImageSource _CurrentEmployeeImage;
public ImageSource CurrentEmployeeImage { get { return _CurrentEmployeeImage; } private set { _CurrentEmployeeImage = value; OnPropertyChanged("CurrentEmployeeImage"); } }//OnPropertyChanged("CurrentTB_EMPLOYEE");
public string CurrentEmployeeImagePath { get; set; }
private List<TB_EMPLOYEE> _TB_EMPLOYEEList;
public List<TB_EMPLOYEE> TB_EMPLOYEEList
{
get { return _TB_EMPLOYEEList; }
set
{
_TB_EMPLOYEEList = value;
RaisePropertyChanged();
}
}
public TB_EMPLOYEE CurrentTB_EMPLOYEE
{
get { return _currentTB_EMPLOYEE; }
set
{
_currentTB_EMPLOYEE = value;
if (_currentTB_EMPLOYEE != null && _currentTB_EMPLOYEE.PHOTO != null)
{ CurrentEmployeeImage = Utility.ConvertByteToImage(_currentTB_EMPLOYEE.PHOTO); }
//OnPropertyChanged("CurrentTB_EMPLOYEE");
RaisePropertyChanged();
}
}
private IList<TB_SETUP_RELIGION> _listRELIGION;
public IList<TB_SETUP_RELIGION> listRELIGION
{
get
{
using (DBMain objDBMain = new DBMain())
{
_listRELIGION = objDBMain.EntTB_SETUP_RELIGION.ToList();
}
return _listRELIGION;
}
}
private IList<string> _listTitles;
public IList<string> listTitles
{
get
{
if (_listTitles == null)
{
_listTitles = new List<string>();
_listTitles.Add("Mr");
_listTitles.Add("Miss");
_listTitles.Add("Mrs");
//_listTitles.Add("Mr");
}
return _listTitles;
}
}
private IList<TB_SETUP_GENDER> _listGENDER;
public IList<TB_SETUP_GENDER> listGENDER
{
get
{
using (DBMain objDBMain = new DBMain())
{
_listGENDER = objDBMain.EntTB_SETUP_GENDER.ToList();
}
return _listGENDER;
}
}
#endregion Properties
#region FormNavigation
private bool isActive;
public override bool IsActive
{
get
{
return this.isActive;
}
set
{
isActive = value;
OnIsActiveChanged();
}
}
protected virtual void OnIsActiveChanged()
{
if (IsActive)
{
_eventAggregator.GetEvent<SubscribeToEvents>().Publish(new Dictionary<string, string>() { { "View", "TB_EMPLOYEE" }, { "FileName", #"Subscribtion to Events" } });
}
else
{
_eventAggregator.GetEvent<UnSubscribeToEvents>().Publish(new Dictionary<string, string>() { { "View", "TB_EMPLOYEE" }, { "FileName", #"UnSubscribtion to Events" } });
}
UnRegisterCommands();
RegisterCommands();
}
public override bool IsNavigationTarget(NavigationContext navigationContext)
{
this.isActive = true;
return this.isActive;
}
public override void OnNavigatedFrom(NavigationContext navigationContext)
{
UnRegisterCommands();
this.isActive = false;
}
public override void OnNavigatedTo(NavigationContext navigationContext)
{
HeaderInfo = "TB_EMPLOYEE";
this.isActive = true;
RegisterCommands();
}
#endregion FormNavigation
}
Finally solve the problem. I was using single Object CurrentTB_EMPLOYEE as current data for my form and ActiveData Item of another List view. this view model handle both form and list views. I just remove CurrentTB_EMPLOYEE from ActiveData Item to my list view and bind them through another object.. when CurrentTB_EMPLOYEE become responsible only for form its start working properly. Thanks every one for your precious time.

Categories