Button appearing at wrong place - c#

I have a button that appears one to the left too much, how do I make it appear under the position I am at? This will probably be something so simple but I really am struggling today, I'm having an awful day today. Someone please help me
public class CognitiveTreeBuilderViewModel : INotifyPropertyChanged
{
private CognitiveTreeRoot root;
private readonly IDiagramBuilder diagramBuilder;
public CognitiveTreeBuilderViewModel(IDiagramBuilder diagramBuilder)
{
this.diagramBuilder = diagramBuilder;
}
public void Bind(CognitiveTreeRoot treeRoot)
{
root = treeRoot;
this.diagramBuilder.BuildDiagram(root);
}
public void Rebuild()
{
this.diagramBuilder.BuildDiagram(root);
}
public void Expand(PropertyNode propertyNode)
{
if (!propertyNode.ScenarioNodes.Any())
{
return;
}
propertyNode.IsExpanded = true;
diagramBuilder.Hide(propertyNode.DiagramId);
foreach (var scenarioNode in propertyNode.ScenarioNodes)
{
diagramBuilder.Show(scenarioNode.DiagramId);
}
}
public void DisplayAddScenarioButton(double p)
{
int propertyNodeIndex = Convert.ToInt32(p/210);
foreach (var property in root.Nodes)
{
property.IsAddButtonVisible = false;
}
if (propertyNodeIndex < root.Nodes.Count)
{
root.Nodes[propertyNodeIndex - 1].IsAddButtonVisible = true;
}
}
public void Collapse(PropertyNode propertyNode)
{
propertyNode.IsExpanded = false;
foreach (var scenarioNode in propertyNode.ScenarioNodes)
{
diagramBuilder.Hide(scenarioNode.DiagramId);
}
diagramBuilder.Show(propertyNode.DiagramId);
}
public void CreateScenario(PropertyNode propertyNode)
{
propertyNode.IsExpanded = true;
propertyNode.AddScenario();
this.diagramBuilder.BuildDiagram(root);
}
public void RenameScenario(ScenarioNode scenarioNode)
{
var shouldEdit = scenarioNode.IsEditing == false;
if (!shouldEdit)
{
scenarioNode.IsEditing = false;
return;
}
foreach (var node in scenarioNode.Parent.ScenarioNodes)
{
node.IsEditing = false;
}
scenarioNode.IsEditing = true;
}
public void ToggleExpanded(PropertyNode propertyNode)
{
if (propertyNode.IsExpanded == true)
{
Collapse(propertyNode);
}
else
{
Expand(propertyNode);
}
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
var handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}

Related

How to copy custom ObservableCollection elements to another custom ObservableCollection?

I created a MTObservableCollection class that derives from ObservableCollection for multithreading. This is how the function looks like:
public class MTObservableCollection<T> : ObservableCollection<T> where T: LogClassa
{
public MTObservableCollection() { }
public override event NotifyCollectionChangedEventHandler CollectionChanged;
protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
NotifyCollectionChangedEventHandler CollectionChanged = this.CollectionChanged;
if (CollectionChanged != null)
foreach (NotifyCollectionChangedEventHandler nh in CollectionChanged.GetInvocationList())
{
DispatcherObject dispObj = nh.Target as DispatcherObject;
if (dispObj != null)
{
Dispatcher dispatcher = dispObj.Dispatcher;
if (dispatcher != null && !dispatcher.CheckAccess())
{
dispatcher.BeginInvoke(
(Action)(() => nh.Invoke(this,
new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset))),
DispatcherPriority.DataBind);
continue;
}
}
nh.Invoke(this, e);
}
}
}
And here is my LogClass
public class LogClass : INotifyPropertyChanged
{
private string timestamp;
private string title;
private string message;
private MTObservableCollection<LogClass> childRowLog = new MTObservableCollection<LogClass>();
public string TimeStamp
{
get { return timestamp; }
set
{
if( timestamp != value )
{
timestamp = value;
OnPropertyChanged("TimeStamp");
}
}
}
public string Title
{
get { return title; }
set
{
if( title!= value )
{
title= value;
OnPropertyChanged("Title");
}
}
}
public string Message
{
get { return message; }
set
{
if( message!= value )
{
message= value;
OnPropertyChanged("Message");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
So if I have two MTObservableCollection collections and I add elements to one of them such as:
public static MTObservableCollection<LogClass> parentLogCollection = new MTObservableCollection<LogClass>();
public MTObservableCollection<LogClass> childLogCollection = new MTObservableCollection<LogClass>();
childLogClass.Add( new LogClass { TimeStamp = "time", Title = "title", Message = "message" } );
Now if I want to add childLogCollection to parentLogCollection, I would do this:
parentLogCollection = new MTObservableCollection<LogClass>(childLogCollection);
I would think I need to create an implementation within the MBObservationCollection class which should be
public MTObservableCollection(MTObservableCollection<T> collection)
{
}
I just don't know what to input into it, how would I perform it?
Try changing the parent of your MTObservableCollection like this:
public MTObservableCollection(MTObservableCollection<T> collection) : base(collection)
{
}

MVVM C#, Moving properties from ViewModel to Model Class

I have folder browser dialog that is bound to the SetterName
private void OnClick(object sender, RoutedEventArgs e)
{
var dialog = new FolderBrowserDialog();
var result = dialog.ShowDialog();
if (result == DialogResult.OK && AssociatedObject.DataContext != null)
{
var propertyInfo = AssociatedObject.DataContext.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public)
.Where(p => p.CanRead && p.CanWrite)
.First(p => p.Name.Equals(SetterName));
string dirName = new DirectoryInfo(dialog.SelectedPath).Name;
FolderName = dirName;
_fileName = System.IO.Path.GetFileName(dirName);
FileName = _fileName;
propertyInfo.SetValue(AssociatedObject.DataContext, dialog.SelectedPath, null);
}
}
And I have the properties set in the ViewModel
public class CommonUseWindowViewModel:INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public Model New { get; set; }
public ICommand Build { get; set; }
public CommonUseWindowViewModel()
{
Build = new DelegateCommand(ClickedMethod);
}
protected async void ClickedMethod()
{
IsEnabled = false;
var gdbName = FolderName;
var styleFol = StyleName;
var envArray = await QueuedTask.Run(() => Geoprocessing.MakeEnvironmentArray(overwriteoutput: true));
var valueArray = await QueuedTask.Run(() => Geoprocessing.MakeValueArray(gdbName, styleFol));
string toolPath = #"c:\staging\ProBaseMapBuilder\BasemapBuilder.tbx\BasemapCreator";
var gpresult1 = await QueuedTask.Run(() => Geoprocessing.ExecuteToolAsync(toolPath, valueArray, envArray));
MessageBox.Show("All Layers Have Been Added to The Map");
IsEnabled = true;
}
private bool _isEnabled = true;
public bool IsEnabled
{
get { return _isEnabled; }
set
{
_isEnabled = value;
OnPropertyChanged("IsEnabled");
}
}
private string _folderName;
public string ShortenedFolderName => Path.GetFileName(_folderName);
public string FolderName
{
get { return _folderName; }
set
{
_folderName = value;
OnPropertyChanged("FolderName");
OnPropertyChanged(nameof(ShortenedFolderName));
}
}
private string _styleName;
public string ShortenedStyleName => Path.GetFileName(_styleName);
public string StyleName
{
get { return _styleName; }
set
{
_styleName = value;
OnPropertyChanged("StyleName");
OnPropertyChanged(nameof(ShortenedStyleName));
}
}
private void OnPropertyChanged(string propertyname)
{
OnPropertyChanged(new PropertyChangedEventArgs(propertyname));
}
private void OnPropertyChanged(PropertyChangedEventArgs args)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, args);
}
}
I would like to move the properties to a Model class but when I do the folder dialog raises an error that there is no matching setter name. I think the problem comes not knowing how to bind this to the view. I am wondering if I am referencing namespace correctly in the view
xmlns:FolderDialog="clr-namespace:BasemapCreator.Behaviors"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:Behaviors="clr-namespace:ArcGIS.Desktop.Internal.Framework.Behaviors;assembly=ArcGIS.Desktop.Framework" x:Class="BasemapCreator.CommonUseWindow"
xmlns:DataContext="clr-namespace:BasemapCreator.Models"
<TextBox x:Name="gdbName" HorizontalAlignment="Left" Height="30" Margin="56,29,0,0" Text="{Binding Model.FolderName, Mode=TwoWay}" VerticalAlignment="Top" Width="282" AllowDrop="True" Visibility="Hidden">
When I add the Model.FolderName to the text box binding I get the error coming from folder dialog.
here is my model
namespace BasemapCreator.Models
{
public class Model:INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private bool _isEnabled = true;
public bool IsEnabled
{
get { return _isEnabled; }
set
{
_isEnabled = value;
OnPropertyChanged("IsEnabled");
}
}
private string _folderName;
public string ShortenedFolderName => Path.GetFileName(_folderName);
public string FolderName
{
get { return _folderName; }
set
{
_folderName = value;
OnPropertyChanged("FolderName");
OnPropertyChanged(nameof(ShortenedFolderName));
}
}
private string _styleName;
public string ShortenedStyleName => Path.GetFileName(_styleName);
public string StyleName
{
get { return _styleName; }
set
{
_styleName = value;
OnPropertyChanged("StyleName");
OnPropertyChanged(nameof(ShortenedStyleName));
}
}
private void OnPropertyChanged(string propertyname)
{
OnPropertyChanged(new PropertyChangedEventArgs(propertyname));
}
private void OnPropertyChanged(PropertyChangedEventArgs args)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, args);
}
}
}
I am using a viewmodel created from a button click
Button Class
namespace BasemapCreator
{
internal class ShowWindow : Button
{
private CommonUseWindow _dlg = null;
protected override void OnClick()
{
if (_dlg != null) return;
_dlg = new CommonUseWindow();
_dlg.Closing += ProWin_Closing;
_dlg.Owner = FrameworkApplication.Current.MainWindow;
_dlg.Show();
}
void ProWin_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
_dlg = null;
}
}
}
In the code behind for the view I have the DataContext set to the viewModel, can I change it and still use the viewmodel?
using ArcGIS.Desktop.Framework.Controls;
using BasemapCreator.ViewModels;
using System;
using System.Windows;
using BasemapCreator.Models;
namespace BasemapCreator
{
/// <summary>
/// Interaction logic for CommonUseWindow.xaml
/// </summary>
public partial class CommonUseWindow : ProWindow
{
private CommonUseWindowViewModel _vm = new CommonUseWindowViewModel();
public CommonUseWindow()
{
InitializeComponent();
this.DataContext = _vm;
}
}
}
Here is the code behind for the view,
In your MainWindow code behind...
using YourProjectName.FolderName;
Then in the MainWindow constructor
InitializeComponent();
//usually this is the only code behind in a view
DataContext = new ClassName();

Writing common properties to a class file in MVVM

I have properties CaretIndex and InputValue im my ViewModel which are used for Highlighting ComboBox Items which matches the text in PART_EditableTextBox of ComboBox.
So, I want them to be in a seperate file. So, I don't have to type them in each and every time I declare a new View. But problem here is that these CaretIndex and InputValue properties's setter part depends on another Class's another property named IsHighlighted and the class may change for each new collection of data.
I have a ViewModel as follows:
public class GroupsViewModel : INotifyPropertyChanged
{
public GroupsViewModel()
{
using (DBEntities db = new DBEntities())
{
GroupsAndCorrespondingEffects = (from g in db.Groups
select new GroupAndCorrespondingEffect
{
GroupName = g.Name,
CorrespondingEffect = g.Type_Effect.Name
}
).ToList();
GroupsAndCorrespondingEffects.Add
(
new GroupAndCorrespondingEffect
{
GroupName = " Primary",
CorrespondingEffect = ""
}
);
GroupsAndCorrespondingEffects = GroupsAndCorrespondingEffects.OrderBy(g => g.GroupName).ToList();
Items = (from e in db.Type_Effect
select e.Name).ToList();
}
}
public static GroupsViewModel CurrentInstance { get { return Instance; } }
private List<GroupAndCorrespondingEffect> _groupsAndCorrespondingEffects;
public List<GroupAndCorrespondingEffect> GroupsAndCorrespondingEffects
{
get
{
return _groupsAndCorrespondingEffects;
}
set
{
_groupsAndCorrespondingEffects = value;
OnPropertyChanged("GroupsAndCorrespondingEffects");
}
}
private int _caretIndex;
public int CaretIndex
{
get { return _caretIndex; }
set
{
_caretIndex = value;
OnPropertyChanged("CaretIndex");
for (int i = 0; i < GroupsAndCorrespondingEffects.Count; i++)
{
string WordToSearch = InputValue;
if (_caretIndex != 0 && _caretIndex > 0)
{
WordToSearch = InputValue.Substring(0, _caretIndex);
}
if (WordToSearch != null)
{
GroupsAndCorrespondingEffects[i].IsHighlighted = GroupsAndCorrespondingEffects[i].GroupName.StartsWith(WordToSearch);
}
}
}
}
private string _inputValue;
public string InputValue
{
get { return _inputValue; }
set
{
_inputValue = value;
OnPropertyChanged("GroupsAndCorrespondingEffects");
for (int i = 0; i < GroupsAndCorrespondingEffects.Count; i++)
{
string WordToSearch = _inputValue;
if (_caretIndex != 0 && _caretIndex > 0 && _caretIndex < _inputValue.Length)
{
WordToSearch = _inputValue.Substring(0, _caretIndex);
}
GroupsAndCorrespondingEffects[i].IsHighlighted = GroupsAndCorrespondingEffects[i].GroupName.StartsWith(WordToSearch);
}
}
}
public void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
The Helper Class that is used to get data in a different format (Get data in Two Columns for a comboBox.) is as below: (This class's IsHighLighted Property is referenced in the setter part of CaretIndex and InputValue.)
public class GroupAndCorrespondingEffect : INotifyPropertyChanged
{
private string _groupName;
public string GroupName
{
get
{
return _groupName;
}
set
{
_groupName = value;
OnPropertyChanged("GroupName");
}
}
private string _correspondingEffect;
public string CorrespondingEffect
{
get
{
return _correspondingEffect;
}
set
{
_correspondingEffect = value;
OnPropertyChanged("CorrespondingEffect");
}
}
private bool _isHighlighted;
public bool IsHighlighted
{
get
{
return _isHighlighted;
}
set
{
_isHighlighted = value;
OnPropertyChanged("IsHighlighted");
}
}
public void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
If I understand your question correctly, what you want to do is move the common bits like CaretIndex, and InputValue to an abstract base class.
Refer to below Sample code to see what I am saying:
Base Class
public abstract class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
private int _caretIndex;
public int CaretIndex
{
get { return _caretIndex; }
set
{
_caretIndex = value;
OnPropertyChanged("CaretIndex");
OnCaretIndexChanged();
}
}
private string _inputValue;
public string InputValue
{
get { return _inputValue; }
set
{
_inputValue = value;
OnPropertyChanged("InputValue");
OnInputValueChanged();
}
}
protected abstract void OnCaretIndexChanged();
protected abstract void OnInputValueChanged();
}
If you check the Setters for CaretIndex and InputValue, they are executing OnCaretIndexChanged and OnInputValueChanged abstract methods respectively - for which you will have implementation in the derived classes.
Now, your GroupViewModel will inherit from ViewModelBase and implement those two abstract methods.
public class GroupsViewModel : ViewModelBase
{
public GroupsViewModel()
{
using (DBEntities db = new DBEntities())
{
GroupsAndCorrespondingEffects = (from g in db.Groups
select new GroupAndCorrespondingEffect
{
GroupName = g.Name,
CorrespondingEffect = g.Type_Effect.Name
}
).ToList();
GroupsAndCorrespondingEffects.Add
(
new GroupAndCorrespondingEffect
{
GroupName = " Primary",
CorrespondingEffect = ""
}
);
GroupsAndCorrespondingEffects = GroupsAndCorrespondingEffects.OrderBy(g => g.GroupName).ToList();
Items = (from e in db.Type_Effect
select e.Name).ToList();
}
}
public static GroupsViewModel CurrentInstance { get { return Instance; } }
private List<GroupAndCorrespondingEffect> _groupsAndCorrespondingEffects;
public List<GroupAndCorrespondingEffect> GroupsAndCorrespondingEffects
{
get
{
return _groupsAndCorrespondingEffects;
}
set
{
_groupsAndCorrespondingEffects = value;
OnPropertyChanged("GroupsAndCorrespondingEffects");
}
}
protected override void OnCaretIndexChanged()
{
for (int i = 0; i < GroupsAndCorrespondingEffects.Count; i++)
{
string wordToSearch = InputValue;
if (CaretIndex != 0 && CaretIndex > 0)
{
wordToSearch = InputValue.Substring(0, CaretIndex);
}
if (wordToSearch != null)
{
GroupsAndCorrespondingEffects[i].IsHighlighted = GroupsAndCorrespondingEffects[i].GroupName.StartsWith(wordToSearch);
}
}
}
protected override void OnInputValueChanged()
{
OnPropertyChanged("GroupsAndCorrespondingEffects");
for (int i = 0; i < GroupsAndCorrespondingEffects.Count; i++)
{
string wordToSearch = InputValue;
if (CaretIndex != 0 && CaretIndex > 0 && CaretIndex < InputValue.Length)
{
wordToSearch = InputValue.Substring(0, CaretIndex);
}
GroupsAndCorrespondingEffects[i].IsHighlighted = GroupsAndCorrespondingEffects[i].GroupName.StartsWith(wordToSearch);
}
}
}
You can follow similar approach if you want to abstract away your IsHighlighted property from class GroupAndCorrespondingEffect.
Hope this helps or gives you some ideas.
UPDATE
Added Class Diagram

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.

Convert DateTime and Boolean to string

I'm a complete C# novice, please excuse my ignorance.
I'm trying to parse string values into a view-model. I'm having difficulty converting the database DateTime and Boolean values into strings as part of the LineOne, LineTwo and LineThree properties. How do I do this?
private void mapChecks()
{
bool FoundResult = false;
// Check if object is loaded
if (Items.Count == 0)
{
//Add everything
foreach (xtn_UnresolvedCheck check in MyChecks)
{
Items.Add(new ItemViewModel
{
LineOne = check.ClientName,
LineTwo = check.NSMDateTime,
LineThree = check.HaveRead,
MyappId = check.MonitoringID
}
);
}
}
ItemViewModel:
namespace App
{
public class ItemViewModel : INotifyPropertyChanged
{
private int _myappId;
public int MyappId
{
get
{
return _myappId;
}
set
{
if (value != _myappId)
{
_myappId = value;
NotifyPropertyChanged("MyappId");
}
}
}
private bool _isFavorite;
public bool IsFavorite
{
get
{
return _isFavorite;
}
set
{
if (value != _isFavorite)
{
_isFavorite = value;
NotifyPropertyChanged("IsFavorite");
}
}
}
private string _lineOne;
public string LineOne
{
get
{
return _lineOne;
}
set
{
if (value != _lineOne)
{
_lineOne = value;
NotifyPropertyChanged("LineOne");
}
}
}
private string _lineTwo;
public string LineTwo
{
get
{
return _lineTwo;
}
set
{
if (value != _lineTwo)
{
_lineTwo = value;
NotifyPropertyChanged("LineTwo");
}
}
}
private string _lineThree;
public string LineThree
{
get
{
return _lineThree;
}
set
{
if (value != _lineThree)
{
_lineThree = value;
NotifyPropertyChanged("LineThree");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (null != handler)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
You should do this
Items.Add( new ItemViewModel
{
LineOne = check.ClientName,
LineTwo = check.NSMDateTime.ToString(),
LineThree = check.HaveRead.ToString(),
MyappId = check.MonitoringID
});
Use ToString();
or cast to string

Categories