I have a function, which takes a long time.
When the function is running, I would like to show some pictures, but this code doesn't work. Why ?
(I must use only framework 4)
This is the code XAML
<Image Width="33" Stretch="Uniform" Source="{Binding ImagePath, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" Grid.Column="0"/>
This is the code
public bool Cmd_TestExe()
{
Thread trd_A = new Thread(MyThreadTask_ShowImg);
Thread_Status = false;
trd_A.Start();
if (My_Slow_Function(sCon) == false) {
displayMessage(Status_Failure);}
}
public void Wait(int sleep)
{
dynamic dFrame = new DispatcherFrame();
ThreadPool.QueueUserWorkItem(state =>
{
Thread.Sleep(sleep);
dFrame.Continue = false;
});
Dispatcher.PushFrame(dFrame);
}
public void MyThreadTask_ShowImg()
{
while (Thread_Status == false) {
Application.Current.Dispatcher.Invoke(new Action(() =>
{
if (Second(Now) % (2) == 0) {
ImagePath = "/Images/exit.png";
Wait(250);
} else {
ImagePath = "/Images/excel.png";
Wait(250);
Console.WriteLine(Now);
}
}));
}
}
...and this is the property
private string _ImagePath { get; set; }
public string ImagePath {
get { return _ImagePath; }
set {
_ImagePath = value;
OnPropertyChanged("ImagePath");
}
}
First, you have to return a bool in your Cmd_TestExe Method.
Second, I've never use DispatcherFrame, but this is how I would do :
public partial class MainWindow : Window
{
Thread myLittleThread;
bool stop;
public string ImageSource
{
set
{
myLittleImage.Source = new BitmapImage(new Uri(value));
}
}
public MainWindow()
{
InitializeComponent();
InitThread();
}
private void InitThread()
{
myLittleThread = new Thread(DoWork);
stop = false;
Application.Current.Exit += MyLittleApplication_Exit;
myLittleThread.Start();
}
private void MyLittleApplication_Exit(object sender,EventArgs e)
{
stop = true;
}
private void DoWork(){
string newImageSource;
while (!stop)
{
if (DateTime.Now.Second % 2 == 0)
{
newImageSource = "SomeRandomFooImage.png";
}
else
{
newImageSource = "MyLittleRandomImage.png";
}
Application.Current.Dispatcher.Invoke(new Action(() =>
{
ImageSource = newImageSource;
}));
Thread.Sleep(250);
}
}
}
and XAML :
<Image Name="myLittleImage" ></Image>
Related
I make a Notes application using WPF with MVVM.
I want to make a counter for each i
So there is a task list, every task has importance (none, regular and important).
I want to make listbox, that displays a count of tasks of each importances and bind it to view (counter for each importance), but i don`t know how. Something like that -
total - 10
none - 5
regular - 3
important - 2
Task Model:
public enum TaskStates
{
None,
Regular,
Important,
}
[DataContractAttribute]
public class Task : INotifyPropertyChanged
{
private string _name;
private string _desc;
private TaskStates taskState;
public SolidColorBrush TaskBG { get; set; }
[DataMember]
public DateTime CreationDate { get; private set; }
[DataMember]
public TaskStates TaskState
{
get { return taskState; }
set
{
TaskBG ??= new SolidColorBrush();
switch (value)
{
case TaskStates.None:
TaskBG.Color = Color.FromRgb(0, 113, 127);
break;
case TaskStates.Important:
TaskBG.Color = Color.FromRgb(180, 60, 60);
break;
case TaskStates.Regular:
TaskBG.Color = Color.FromRgb(53, 165, 75);
break;
}
taskState = value;
OnPropertyChanged(nameof(TaskState));
}
}
[DataMember]
public string Name
{
get => _name;
set
{
_name = value;
OnPropertyChanged(nameof(Name));
}
}
[DataMember]
public string Description
{
get => _desc;
set
{
_desc = value;
OnPropertyChanged(nameof(Description));
}
}
public Task(string name, string desc,DateTime creationDate, TaskStates taskState)
{
this._name = name;
this._desc = desc;
CreationDate = creationDate;
TaskState = taskState;
}
public Task()
{
}
protected void OnPropertyChanged ([CallerMemberName]string prop = "") => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(prop));
public event PropertyChangedEventHandler PropertyChanged;
}
ViewModel:
class TaskViewModel : INotifyPropertyChanged
{
public Task CurrentTask { get; set; }
public DateTime CurrentDate { get; set; }
IDialogService dialogService;
IFileService fileService;
private TaskCommand addTask;
private TaskCommand removeTask;
private TaskCommand saveCommand;
private TaskCommand openCommand;
private TaskCommand clearCommand;
public ObservableCollection<Task> Tasks { get; set; }
#region Command Properties
public TaskCommand AddCommand
{
get
{
return addTask ?? (addTask = new TaskCommand(
new Action<object>(obj =>
{
Tasks.Add((obj as Task) ?? new Task("Header", "smth", CurrentDate, TaskStates.None));
})
));
}
}
public TaskCommand RemoveCommand
{
get
{
return removeTask ?? (removeTask = new TaskCommand(
new Action<object>(obj =>
{
if (CurrentTask != null)
Tasks.Remove(CurrentTask);
}), new Func<object, bool>(obj => Tasks.Count > 0)
));
}
}
public TaskCommand SaveCommand
{
get
{
return saveCommand ?? (saveCommand = new TaskCommand(
new Action<object>(obj =>
{
try
{
if (dialogService.SaveFileDialog() == true)
{
fileService.Save(Tasks.ToList(), dialogService.FilePath);
dialogService.ShowMessage("File Saved");
}
}
catch (Exception ex)
{
dialogService.ShowMessage(ex.Message);
}
}),
new Func<object, bool>(obj => Tasks.Count > 0)));
}
}
public TaskCommand OpenCommand
{
get
{
return openCommand ?? (openCommand = new TaskCommand(
new Action<object>(obj =>
{
try
{
if (dialogService.OpenFileDialog())
{
var newTasks = fileService.Open(dialogService.FilePath);
if (newTasks.Count > 0)
{
Tasks.Clear();
foreach (var item in newTasks)
{
Tasks.Add(item);
}
}
}
}
catch (Exception ex)
{
dialogService.ShowMessage(ex.Message);
}
}
)));
}
}
public TaskCommand ClearCommand
{
get
{
return clearCommand ?? (clearCommand = new TaskCommand
(
new Action<object>(obj =>
{
var res = MessageBox.Show("Are you Sure?", "Caution", MessageBoxButton.YesNo, MessageBoxImage.Warning);
if (res == MessageBoxResult.Yes)
Tasks.Clear();
}),
new Func<object, bool>(obj => Tasks.Count > 0)
));
}
}
#endregion
public TaskViewModel()
{
CurrentDate = DateTime.Now;
fileService = new JsonFileService();
dialogService = new DefaultDialogService();
Tasks = new ObservableCollection<Task>()
{
new Task("Important", "Test",CurrentDate,TaskStates.Important),
new Task("Regular", "Test",CurrentDate,TaskStates.None),
};
}
protected void OnPropertyChanged([CallerMemberName] string prop = "") => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(prop));
public event PropertyChangedEventHandler PropertyChanged;
}
Use a ValueConverter to accomplish this.
public class TaskStateCountConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
=> $"{parameter} - {((IEnumerable<Task>)value).Count(task => task.TaskState == (TaskStates)parameter)}";
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
=> throw new NotImplementedException();
}
XAML (you said you wanted a ListBox):
<Window.Resources>
<local:TaskStateCountConverter x:Key="TaskStateCountConverter"/>
</Window.Resources>
<Grid>
<ListBox>
<ListBoxItem Content="{Binding Tasks.Count}"/>
<ListBoxItem Content="{Binding Tasks,
Converter={StaticResource TaskStateCountConverter},
ConverterParameter={x:Static local:TaskStates.None}}"/>
<ListBoxItem Content="{Binding Tasks,
Converter={StaticResource TaskStateCountConverter},
ConverterParameter={x:Static local:TaskStates.Regular}}"/>
<ListBoxItem Content="{Binding Tasks,
Converter={StaticResource TaskStateCountConverter},
ConverterParameter={x:Static local:TaskStates.Important}}"/>
</ListBox>
</Grid>
ViewModel:
public class TaskViewModel : INotifyPropertyChanged
{
// unchanged parts skipped
public TaskViewModel()
{
Tasks.CollectionChanged += OnTasksChanged;
}
private void OnTasksChanged(object sender, EventArgs e)
=> OnPropertyChanged(nameof(Tasks));
It was a bit trickier than I first thought because the converted values are not updated without the event handler (Tasks.Count is).
And while you're about it, you could also create a ValueConverter for your coloring logic.
Edit
To update TaskViewModel from within CurrentTask:
public class TaskViewModel : INotifyPropertyChanged
{
// unchanged parts skipped
private Task _currentTask;
public Task CurrentTask
{
get => _currentTask;
set
{
if (value != _currentTask)
{
if (_currentTask != null)
{
_currentTask.PropertyChanged -= OnCurrentTaskChanged;
}
_currentTask = value;
_currentTask.PropertyChanged += OnCurrentTaskChanged;
}
}
}
private void OnCurrentTaskChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(Task.TaskState))
{
OnPropertyChanged(nameof(Tasks));
}
}
}
I am building a game in xamarin in which I am trying to show a DisplayAlert Popup when the game is finished (after 8 seconds). However as the time gets to zero it wont show.
If i put the DisplayAlert at the beginning of the time it works fine.
Can you please explain, why this is the case?
The DisplayAlert line is located in the "OnTimedEvent" Method at the end of the code in this ViewModel:
using System;
using System.Diagnostics;
using System.Timers;
using CBTGAME1.Models;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace CBTGAME1.ViewModels
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class GamePageViewModel : ObservableObject
{
Animals aninames = new Animals();
Timer timer;
private int countSecond;
public int CountSecond
{
get { return countSecond; }
set
{
countSecond = value;
OnPropertyChanged(nameof(CountSecond));
}
}
private string nowanimal = null;
public string Nowanimal
{
get { return nowanimal; }
set {
nowanimal = value;
OnPropertyChanged(nameof(Nowanimal));
}
}
public Command Generate { get; }
public Command button1 { get; }
public Command button2 { get; }
public Command button3 { get; }
private int yourscore = 0;
public int Yourscore
{
get { return yourscore; }
set { yourscore = value;
OnPropertyChanged(nameof(Yourscore));
}
}
private string firstb;
private string secondb;
private string thirdb;
public string Firstb
{
get { return firstb; }
set
{
firstb = value;
OnPropertyChanged(nameof(Firstb));
}
}
public string Secondb
{
get { return secondb; }
set
{
secondb = value;
OnPropertyChanged(nameof(Secondb));
}
}
public string Thirdb
{
get { return thirdb; }
set
{
thirdb = value;
OnPropertyChanged(nameof(Thirdb));
}
}
public GamePageViewModel()
{
RndAll();
timer = new Timer();
settimer();
button1 = new Command(() =>
{BtnOperation(firstb); });
button2 = new Command(() =>
{BtnOperation(secondb); });
button3 = new Command(() =>
{BtnOperation(thirdb); });
}
public void BtnOperation(string btname)
{
if (btname == Nowanimal)
Yourscore = Yourscore + 1;
else Yourscore = Yourscore - 1;
RndAll();
}
public void RndAll()
{
Random rnd = new Random();
Nowanimal = aninames.Animalss[rnd.Next(0, 3)];
int i = rnd.Next(0, 3);
Firstb = aninames.Animalss[i];
if (i == 2) i = 0;
else i++;
Secondb = aninames.Animalss[i];
if (i == 2) i = 0;
else i++;
Thirdb = aninames.Animalss[i];
}
public void settimer()
{
CountSecond = 8;
timer.Interval = 1000;
timer.Elapsed += OnTimedEvent;
timer.Enabled = true;
}
private void OnTimedEvent(object sender, ElapsedEventArgs e)
{
CountSecond--;
if (CountSecond == 0)
{
timer.Stop();
App.Current.MainPage.DisplayAlert("finished", "have a good day", "Exit");
}
}
}
}
1) DisplayAlert returns a Task, so await it
2) Call it on the main/ui thread
Device.BeginInvokeOnMainThread (async() => {
await App.Current.MainPage.DisplayAlert("finished", "have a good day", "Exit");
});
I am trying to implement a searchbar using MVVM in Xamarin.forms. so far I have managed to borrow some code from around the internet and it seems to do go through the motions of the search. the only issue is I don't know what code to put in the command.
I would like the search bar to search recipeNames from a list of Recipes. this information is all stored on a local database and displayed using an observable collection.
please can you help me work it out.
XAML
<SearchBar x:Name="SearchBar"
Placeholder="Search"
SearchCommand="{Binding SearchCommand}"
SearchCommandParameter="{Binding Text, Source={x:Reference SearchBar}}"
Text="{Binding SearchText, Mode=TwoWay}">
<SearchBar.Behaviors>
<local:TextChangedBehavior />
</SearchBar.Behaviors>
</SearchBar>
<ListView x:Name="ListViewItems"
ItemsSource="{Binding Recipes}"
IsPullToRefreshEnabled="True"
Refreshing="ListViewItems_Refreshing"
SelectedItem="{Binding SelectedRecipe}">
Text changed Behaviour
class TextChangedBehavior: Behavior<Xamarin.Forms.SearchBar>
{
protected override void OnAttachedTo(Xamarin.Forms.SearchBar bindable)
{
base.OnAttachedTo(bindable);
bindable.TextChanged += Bindable_TextChanged;
}
protected override void OnDetachingFrom(Xamarin.Forms.SearchBar bindable)
{
base.OnDetachingFrom(bindable);
bindable.TextChanged -= Bindable_TextChanged;
}
private void Bindable_TextChanged(object sender, TextChangedEventArgs e)
{
((Xamarin.Forms.SearchBar)sender).SearchCommand?.Execute(e.NewTextValue);
}
}
and viewModel
public class RecipeListViewModel : ObservableCollection<Recipe>
{
private ObservableCollection<Recipe> Recipes {get; set;}
public INavigation Navigation { get; internal set; }
public ICommand NewAddPage { get; protected set; }
public RecipeListViewModel(INavigation navigation)
{
this.Navigation = navigation;
Recipes = new ObservableCollection<Recipe>();
this.NewAddPage = new Command(async () => await CreateNewAddPage());
Init();
}
// Gets all recipes from the database and adds them to the observable collection
private void Init()
{
var enumarator = App.RecipeDbcontroller.GetRecipe();
if (enumarator == null)
{
App.RecipeDbcontroller.SaveRecipe(new Recipe { RecipeName = "Moussaka", Serves = 6, PrepTime = "30", CookTime = "2 Hours", MealType = "Dinner" });
enumarator = App.RecipeDbcontroller.GetRecipe();
}
while (enumarator.MoveNext())
{
//cleans database of all empty records
if (enumarator.Current.RecipeName == null || enumarator.Current.CookTime == null)
{
App.RecipeDbcontroller.DeleteRecipe(enumarator.Current.RecipeID);
}
else
Add(enumarator.Current);
}
}
private ICommand _searchCommand;
public ICommand SearchCommand
{
get
{
return _searchCommand ?? (_searchCommand = new Command<string>((text) =>
{
**// THIS IS WHAT I DON'T KNOW WHAT TO DO**
}));
}
}
private string _searchText { get; set; }
public string SearchText
{
get { return _searchText; }
set
{
if (_searchText != value)
{
_searchText = value;
}
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
RecipeDatabaseController Class
public RecipeDatabaseController()
{
this.database = DependencyService.Get<ISQLite>().GetConnection();
this.database.CreateTable<Recipe>();
}
//Recipe CRUD
public IEnumerator<Recipe> GetRecipe()
{
lock (locker)
{
if (database.Table<Recipe>().Count() == 0)
{
return null;
}
else
{
return this.database.Table<Recipe>().GetEnumerator();
}
}
}
public IEnumerator<Recipe> GetRecipeBySearchTerm(text)
{
var enumarator = GetRecipe();
lock (locker)
{
while (enumarator.MoveNext)
{
if(enumarator.Current.RecipeName.Contains(text)
return this.
}
}
}
public int SaveRecipe(Recipe recipe)
{
lock (locker)
{
if (recipe.RecipeID != 0)
{
this.database.Update(recipe);
return recipe.RecipeID;
}
else
{
return this.database.Insert(recipe);
}
}
}
public int DeleteRecipe(int Id)
{
lock (locker)
{
return this.database.Delete<Recipe>(Id);
}
}
right so the search command ought to look like this.
public ICommand SearchCommand => _searchCommand ?? (_searchCommand = new Command<string>((text) =>
{
if (text.Length >=1)
{
Recipes.Clear();
Init();
var suggestions = Recipes.Where(c => c.RecipeName.ToLower().StartsWith(text.ToLower())).ToList();
Recipes.Clear();
foreach (var recipe in suggestions)
Recipes.Add(recipe);
}
else
{
Recipes.Clear();
Init();
ListViewVisible = true;
SuggestionsListViewVisible = false;
}
}));
using System.Linq;
//Recipe CRUD
public IEnumerable<Recipe> GetRecipe()
{
lock (locker)
{
return this.database.Table<Recipe>();
}
}
public IEnumerable<Recipe> GetRecipeBySearchTerm(string text)
{
var recipes = GetRecipe();
lock (locker)
{
return recipes.Where(m => m.RecipeName.ToLower().Contains(text));
}
}
Add the using System.Linq reference
Change those two methods and return IEnumerable
Note. RecipeName is the property you want to filter your Recipe with.
And your search command as below
private ICommand _searchCommand;
public ICommand SearchCommand
{
get
{
return _searchCommand ?? (_searchCommand = new Command<string>((text) =>
{
var filteredRecipes = App.RecipeDbcontroller.GetRecipeBySearchTerm(text);
recipes.Clear();
foreach(var recipe in filteredRecipes )
recipes.Add(recipe);
}));
}
}
I have not tested this code, so not sure where I might get errors, but you can work out the rest because the logic is given to you
Good luck
I created a reference to load big data into a datagrid with a dapper extension. I have a Behavior that detects when the scroll is then down load the following data using this RelayCommand:
XAML in Datagrid Properties :
Behavior:ScrollViewerMonitor.AtEndCommand="{Binding LoadCommand}"
My Behavior (Detect when scroll is down) :
public class ScrollViewerMonitor
{
public static DependencyProperty AtEndCommandProperty
= DependencyProperty.RegisterAttached(
"AtEndCommand", typeof(ICommand),
typeof(ScrollViewerMonitor),
new PropertyMetadata(OnAtEndCommandChanged));
public static ICommand GetAtEndCommand(DependencyObject obj)
{
return (ICommand)obj.GetValue(AtEndCommandProperty);
}
public static void SetAtEndCommand(DependencyObject obj, ICommand value)
{
obj.SetValue(AtEndCommandProperty, value);
}
public static void OnAtEndCommandChanged(
DependencyObject d, DependencyPropertyChangedEventArgs e)
{
FrameworkElement element = (FrameworkElement)d;
if (element != null)
{
element.Loaded -= element_Loaded;
element.Loaded += element_Loaded;
}
}
static void element_Loaded(object sender, RoutedEventArgs e)
{
FrameworkElement element = (FrameworkElement)sender;
element.Loaded -= element_Loaded;
ScrollViewer scrollViewer = FindChildOfType<ScrollViewer>(element);
if (scrollViewer == null)
{
// throw new InvalidOperationException("ScrollViewer not found.");
return;
}
var dpd = DependencyPropertyDescriptor.FromProperty(ScrollViewer.VerticalOffsetProperty, typeof(ScrollViewer));
dpd.AddValueChanged(scrollViewer, delegate (object o, EventArgs args)
{
bool atBottom = scrollViewer.VerticalOffset
>= scrollViewer.ScrollableHeight;
if (atBottom)
{
var atEnd = GetAtEndCommand(element);
if (atEnd != null)
{
atEnd.Execute(null);
}
}
});
}
static T FindChildOfType<T>(DependencyObject root) where T : class
{
var queue = new Queue<DependencyObject>();
queue.Enqueue(root);
while (queue.Count > 0)
{
DependencyObject current = queue.Dequeue();
for (int i = VisualTreeHelper.GetChildrenCount(current) - 1; 0 <= i; i--)
{
var child = VisualTreeHelper.GetChild(current, i);
var typedChild = child as T;
if (typedChild != null)
{
return typedChild;
}
queue.Enqueue(child);
}
}
return null;
}
}
My ViewModel with LoadCommand :
//Init mmy ObservableCollection for DataGrid
var myObservableCollection = new ObservableCollection<Mouvement_Brouillard>();
//Init my Object
//Parameters(NumberPerPage,Conditions,OrderBy,Connection)
var myReference = new Paged2<Mouvement_Brouillard>(150, "", "Swmo_Id", new ConnectionProvider());
//Load First Datas
myReference.AddDatas(myObservableCollection);
//Call LoadCommand when Scroll is down
LoadCommand = new RelayCommand<object>(myReference.LoadCommand(myObservableCollection));
And my reference Paged2 (AddData in ObservableCollection and execute LoadCommand:
public class Paged2<T>
{
private T Value { get; set; }
public int NumberPage { get; set; }
public int RowsPerPage { get; set; }
public string Conditions { get; set; }
public string OrderBy { get; set; }
public ConnectionProvider Cnn { get; set; }
public static bool Busy;
public Paged2(int _RowsPerPage, string _Conditions, string _OrdeBy, ConnectionProvider _Cnn)
{
this.RowsPerPage = _RowsPerPage;
this.Conditions = _Conditions;
this.OrderBy = _OrdeBy;
this.NumberPage = 1;
this.Cnn = _Cnn;
}
public async void AddDatas(ObservableCollection<T> myList)
{
IEnumerable<T> myNewBlocList;
//DAL
using (var myCnn = this.Cnn.GetOpenConnection())
{
myNewBlocList = await myCnn.GetListPagedAsync<T>(this.NumberPage, this.RowsPerPage, this.Conditions, this.OrderBy);
}
NumberPage++;
foreach (var Item in myNewBlocList)
myList.Add(Item);
}
public Action<object> LoadCommand(Ref<ObservableCollection<T>> myList)
{
return new Action<object>(
obj =>
{
if (Busy)
return;
Busy = true;
System.Threading.ThreadPool.QueueUserWorkItem(
delegate
{
Application.Current.Dispatcher.BeginInvoke(new Action(
delegate
{
AddDatas(myList);
Busy = false;
}));
});
});
}
public class Ref<T>
{
public Ref() { }
public Ref(T value) { Value = value; }
public T Value { get; set; }
public override string ToString()
{
T value = Value;
return value == null ? "" : value.ToString();
}
public static implicit operator T(Ref<T> r) { return r.Value; }
public static implicit operator Ref<T>(T value) { return new Ref<T>(value); }
}
}
Everything works but since I outsource (place in another file ) method LoadCommand the next part of the code no longer works :
public Action<object> LoadCommand(Ref<ObservableCollection<T>> myList)
{
return new Action<object>(
obj =>
{
if (Busy)
return;
Busy = true;
System.Threading.ThreadPool.QueueUserWorkItem(
delegate
{
Application.Current.Dispatcher.BeginInvoke(new Action(
delegate
{
AddDatas(myList);
Busy = false;
}));
});
});
}
Below is my View code. My List is being set and updated at back-end but its not reflected in front-end even though I bonded it with ListItems.
Can you please tell why is this happening? Please tell me if you need other files.
ListOfVehicle.xaml
<Window x:Class="Seris.ListOfVehicle"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="VehicalForm" Height="600" Width="700">
<Grid>
<Label Content="Add Vehicle" HorizontalAlignment="Left" Height="27" Margin="261,8,0,0" VerticalAlignment="Top" Width="85" FontWeight="Bold" FontSize="12"/>
<Label Content="SERIS CAD" HorizontalAlignment="Left" Height="30" Margin="53,8,0,0" VerticalAlignment="Top" Width="84" FontWeight="Bold"/>
<Menu x:Name="ListOfPersonnnel" HorizontalAlignment="Left" Height="32" Margin="10,35,0,0" VerticalAlignment="Top" Width="603">
<MenuItem Header="Manage Vehicle >>" />
</Menu>
<Button Name="Add_Button" CommandParameter="add" Command="{Binding OpenAddWindow_Command}" Content="Add" Height="28" Width="81" Margin="246,396,315,46"/>
<Button Name="Replace_Button" CommandParameter="replace" Command="{Binding RemoveButton_Command}" IsEnabled="{Binding isEnableReplaceButton, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" Content="Replace" Height="28" Width="81" Margin="345,396,216,46"/>
<Button Name="Remove_Button" CommandParameter="remove" Command="{Binding ReplaceButton_Command}" IsEnabled="{Binding isEnableReplaceButton, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" Content="Remove" Height="28" Width="81" Margin="442,396,119,46"/>
<Label x:Name="Error_Label" Content="{Binding ErrorMessage, UpdateSourceTrigger=PropertyChanged}" Foreground="Red" HorizontalAlignment="Left" Height="30" Width="100" Margin="88,206,0,224"/>
<ListView Name ="Grid" Margin="104,67,185,226" >
<DataGrid Name="DG" ItemsSource="{Binding ListItems, UpdateSourceTrigger=PropertyChanged}" SelectedItem="{Binding SelectedRow, Mode=TwoWay}" GridLinesVisibility="None" IsReadOnly="True" AutoGenerateColumns="False" BorderThickness="0">
<DataGrid.Columns>
<DataGridTextColumn Header="Vehical No" Binding="{Binding VehicalNo}"/>
<DataGridTextColumn Header="Model" Binding="{Binding Model}" />
<DataGridTextColumn Header="ManufacturingDate" Binding="{Binding ManufacturingDate}" />
<DataGridTextColumn Header="IUNo" Binding="{Binding IUNo}" />
<DataGridTextColumn Header="Personnel" Binding="{Binding PersonnelNameSelected}" />
<DataGridTextColumn Header="Unique No" Binding="{Binding UniqueNo}"/>
</DataGrid.Columns>
</DataGrid>
</ListView>
</Grid>
VehicleMainViewModel
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Seris.Models;
using System.Collections.ObjectModel;
using System.Windows.Input;
using Seris.Commands;
using Seris.ViewModels;
using System.Windows;
using System.Windows.Controls;
using System.Threading;
using System.ComponentModel;
using Seris.Views;
namespace Seris.ViewModels
{
public class VehicleMainViewModel : ObservableObject
{
#region Getters-Setters
// Static Variables...
private static bool _IsEnableReplaceButton;
public static bool IsEnableReplaceButton
{
get { return _IsEnableReplaceButton; }
set { _IsEnableReplaceButton = value; }
}
// Non-Static Variables...
private string _VehicleNo_Error;
public string VehicleNo_Error
{
get { return _VehicleNo_Error; }
set { _VehicleNo_Error = value; OnPropertyChanged("VehicleNo_Error"); }
}
private string _Model_Error;
public string Model_Error
{
get { return _Model_Error; }
set { _Model_Error = value; OnPropertyChanged("Model_Error"); }
}
private string _ManufacturingDate_Error;
public string ManufacturingDate_Error
{
get { return _ManufacturingDate_Error; }
set { _ManufacturingDate_Error = value; OnPropertyChanged("ManufacturingDate_Error"); }
}
private string _IUNo_Error;
public string IUNo_Error
{
get { return _IUNo_Error; }
set { _IUNo_Error = value; OnPropertyChanged("IUNo_Error"); }
}
private string _Personnel_Error;
public string Personnel_Error
{
get { return _Personnel_Error; }
set { _Personnel_Error = value; OnPropertyChanged("Personnel_Error"); }
}
private string _ErroMesage;
public string ErrorMessage
{
get { return _ErroMesage; }
set
{
_ErroMesage = value; OnPropertyChanged("ErrorMessage");
if (ErrorMessage.Trim() == "" || ErrorMessage == null)
HelpVisibility = "hidden";
else
HelpVisibility = "visible";
}
}
private string _HelpVisibility;
public string HelpVisibility
{
get { return _HelpVisibility; }
set { _HelpVisibility = value; OnPropertyChanged("HelpVisibility"); }
}
private static AddVehicle _addVehicle;
public static AddVehicle addVehicle
{
get
{
return _addVehicle;
}
set
{
_addVehicle = value;
}
}
// Form Components
private Guid? _UniqueNo;
public Guid? UniqueNo
{
get { return _UniqueNo; }
set
{
if (value == null || (!value.Equals(_UniqueNo)))
{
_UniqueNo = value;
OnPropertyChanged("UniqueNo");
}
}
}
private string _VehicleNo;
public string VehicleNo
{
get { return _VehicleNo; }
set
{
if (value == null || (!value.Equals(_VehicleNo)))
{
_VehicleNo = value;
EditText = _VehicleNo;
OnPropertyChanged("VehicleNo");
validateSpecificData(1);
}
}
}
private string _Model;
public string Model
{
get { return _Model; }
set
{
if (value == null || (!value.Equals(_Model)))
{
_Model = value;
EditText = _Model;
OnPropertyChanged("Model");
validateSpecificData(2);
}
}
}
private DateTime? _ManufacturingDate;
public DateTime? ManufacturingDate
{
get { return _ManufacturingDate; }
set
{
if (value == null || (!value.Equals(_ManufacturingDate)))
{
_ManufacturingDate = value;
EditText = _ManufacturingDate.ToString();
OnPropertyChanged("ManufacturingDate");
validateSpecificData(3);
}
}
}
private string _IUNo;
public string IUNo
{
get { return _IUNo; }
set
{
if (value == null || (!value.Equals(_IUNo)))
{
_IUNo = value;
EditText = _IUNo;
OnPropertyChanged("IUNo");
validateSpecificData(4);
}
}
}
private string _PersonnelNameSelected;
public string PersonnelNameSelected
{
get { return _PersonnelNameSelected; }
set
{
if (value != _PersonnelNameSelected)
{
_PersonnelNameSelected = value;
EditText = _PersonnelNameSelected;
OnPropertyChanged("PersonnelNameSelected");
}
}
}
private ObservableCollection<string> _PersonnelName;
public ObservableCollection<string> PersonnelName
{
get { return _PersonnelName; }
set
{
if (value != _PersonnelName)
{
_PersonnelName = value;
EditText = _VehicleNo;
OnPropertyChanged("PersonnelName");
}
}
}
private ObservableCollection<VehicleModel> _listItems;
public ObservableCollection<VehicleModel> ListItems
{
get { return _listItems; }
set
{
if (value == null || (!value.Equals(_listItems)))
{
_listItems = value;
}
}
}
// Other Variables
private string _EditText;
public string EditText
{
get { return _EditText; }
set
{
if (value != _EditText)
{
_EditText = value;
OnPropertyChanged("EditText");
}
}
}
private VehicleModel _SelectedRow;
public VehicleModel SelectedRow
{
get { return _SelectedRow; }
set
{
if (value != _SelectedRow)
{
_SelectedRow = value;
OnPropertyChanged("SelectedRow");
if (SelectedRow != null)
{
UniqueNo = _SelectedRow.UniqueNo;
VehicleNo = _SelectedRow.VehicleNo;
Model = _SelectedRow.Model;
ManufacturingDate = _SelectedRow.ManufacturingDate;
IUNo = _SelectedRow.IUNo;
PersonnelNameSelected = _SelectedRow.PersonnelNameSelected;
_IsEnableReplaceButton = true;
}
}
}
}
private int _Progress;
public int Progress
{
get { return _Progress; }
set { _Progress = value; OnPropertyChanged("Progress"); }
}
#endregion
// Command Variables
private ICommand _saveButton_Command;
public ICommand SaveButton_Command
{
get { return _saveButton_Command; }
set { _saveButton_Command = value; }
}
private ICommand _ReplaceButton_Command;
public ICommand ReplaceButton_Command
{
get { return _ReplaceButton_Command; }
set { _ReplaceButton_Command = value; }
}
private ICommand _RemoveButton_Command;
public ICommand RemoveButton_Command
{
get { return _RemoveButton_Command; }
set { _RemoveButton_Command = value; }
}
private ICommand _OpenAddWindow_Command;
public ICommand OpenAddWindow_Command
{
get { return _OpenAddWindow_Command; }
set { _OpenAddWindow_Command = value; }
}
#region Methods
//Static Methods...
public static void showMessage(string message)
{
MessageBox.Show(message);
}
//Non-Static Methods...
public void SaveToList(object o1)
{
try
{
// Setting Flags
ErrorMessage = "";
// To Verify Validations
validateAllData();
// ProgressBar
//Progress = 0;
//ProgressBar();
// Adding a Record
ListItems.Add(new VehicleModel(VehicleNo, Model, ManufacturingDate, IUNo, PersonnelNameSelected));
// Setting Flags etc.
IsEnableReplaceButton = false;
CloseAdd();
// Clearing Form
UniqueNo = null;
VehicleNo = null;
Model = null;
ManufacturingDate = null;
IUNo = null;
PersonnelNameSelected = null;
}
catch (Exception ex)
{
Progress = 0;
ErrorMessage = ex.Message;
}
}
public void ReplaceToList(object o1)
{
try
{
VehicleModel vm = ListItems.First(x => x.UniqueNo == UniqueNo);
int indexToRemove = ListItems.IndexOf(vm);
// Setting Flags
ErrorMessage = "";
// To Verify Validations
validateAllData();
// ProgressBar
Progress = 0;
ProgressBar();
// Replacing Record
ListItems.Insert(indexToRemove + 1, vm);
ListItems.RemoveAt(indexToRemove);
// Clearing Form
VehicleNo = null;
Model = null;
ManufacturingDate = null;
IUNo = null;
PersonnelNameSelected = null;
// Setting Flags etc.
ErrorMessage = "";
IsEnableReplaceButton = false;
}
catch (Exception ex)
{
ErrorMessage = ex.Message;
}
}
public void RemoveList(object o1)
{
VehicleModel vm = ListItems.First(x => x.UniqueNo == UniqueNo);
int indexToRemove = ListItems.IndexOf(vm);
ErrorMessage = "";
try
{
// Setting Flags
ErrorMessage = "";
Progress = 0;
// Removing Selected Record
ListItems.RemoveAt(indexToRemove);
// Clearing Form
VehicleNo = null;
Model = null;
ManufacturingDate = null;
IUNo = null;
PersonnelNameSelected = null;
// Setting Flags etc.
ErrorMessage = "";
IsEnableReplaceButton = false;
}
catch (Exception ex)
{
ErrorMessage = ex.Message;
}
}
void ProgressBar()
{
BackgroundWorker worker = new BackgroundWorker();
worker.WorkerReportsProgress = true;
worker.DoWork += worker_DoWork;
worker.ProgressChanged += worker_ProgressChanged;
worker.RunWorkerAsync();
}
void worker_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 1; i <= 100; i++)
{
(sender as BackgroundWorker).ReportProgress(i);
Thread.Sleep(5);
}
}
void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
Progress = e.ProgressPercentage;
}
public void validateAllData()
{
VehicleModel tempObject = new VehicleModel(VehicleNo, Model, ManufacturingDate, IUNo, PersonnelNameSelected);
}
public void validateSpecificData(int ErrorCode)
{
VehicleModel tempObject = new VehicleModel();
switch(ErrorCode)
{
case 1: tempObject.VehicleNo=VehicleNo;break;
case 2: tempObject.Model=Model;break;
case 3: tempObject.ManufacturingDate=ManufacturingDate;break;
case 4: tempObject.IUNo=IUNo;break;
}
tempObject.ValidateSpecificData(this, ErrorCode);
}
public void OpenAdd(object o1)
{
if(addVehicle==null)
{
addVehicle = new AddVehicle();
}
addVehicle.Show();
}
public void CloseAdd()
{
if (addVehicle != null)
{
addVehicle.Close();
addVehicle = null;
}
}
#endregion
#region Constructors
public VehicleMainViewModel()
{
// Initialization
//VehicleModel vm = new VehicleModel();
ListItems = new ObservableCollection<VehicleModel>();
PersonnelName = ListOfPersonnelViewModel.PersonNameList_Updating;
//PersonnelName = new ObservableCollection<string>() { "ABC", "DEF", "GHI" };
// Setting Flags
ErrorMessage = "";
IsEnableReplaceButton = false;
// Commands Initialization
SaveButton_Command = new RelayCommand(new Action<object>(SaveToList));
ReplaceButton_Command = new RelayCommand(new Action<object>(ReplaceToList));
RemoveButton_Command = new RelayCommand(new Action<object>(RemoveList));
OpenAddWindow_Command = new RelayCommand(new Action<object>(OpenAdd));
}
#endregion
}
}
Probably you may have not created Singleton instance so possibility of creating multiple instance for each window. Below is an example for your ViewModel Singleton.
private static VehicleMainViewModel _Instance;
public static VehicleMainViewModel getInstance
{
get
{
if(_Instance==null)
{
_Instance = new VehicleMainViewModel();
}
return _Instance;
}
}