I get the error message which is written in the title.
My XAML looks like this:
<Window x:Class="LINQ3_Test_aus_LINQ2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:LINQ3_Test_aus_LINQ2"
Title="MainWindow" Height="450" Width="800">
<Window.DataContext>
<local:MainViewModel/>
</Window.DataContext>
<Grid>
<TextBox x:Name="txt_LiefNr" HorizontalAlignment="Left" Height="26" Margin="55,50,0,0" TextWrapping="Wrap" Text="{Binding LiefNr}" VerticalAlignment="Top" Width="125"/>
<TextBox x:Name="txt_LiefName" HorizontalAlignment="Left" Height="26" Margin="55,93,0,0" TextWrapping="Wrap" Text="{Binding LiefName}" VerticalAlignment="Top" Width="125"/>
<Button x:Name="btn_LiefNr" Content="Button" HorizontalAlignment="Left" Height="26" Margin="215,50,0,0" VerticalAlignment="Top" Width="116" Command="{Binding LookupCommand}"/>
</Grid>
and my MainViewModel.cs like this:
using GalaSoft.MvvmLight.Command;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace LINQ3_Test_aus_LINQ2
{
public class MainViewModel : INotifyPropertyChanged
{
private string _liefNr;
private string _liefName;
public ICommand LookupCommand { get; set; }
public string LiefNr
{
get { return _liefNr; }
set
{
_liefNr = value;
OnPropertyChanged();
}
}
public string LiefName
{
get { return _liefName; }
set
{
_liefName = value;
OnPropertyChanged();
}
}
public MainViewModel()
{
LookupCommand = new RelayCommand(Lookup);
}
private void Lookup()
{
Excel.OpenFile();
LiefName = Excel.Fill(LiefNr);
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
I cant find a solution to this error thats why i am asking you. I have checked multiple times if something is wrong the the names, but there is not its all written correctly.
Very new to WPF coding using MVVM. Tried making a simple calculator in WPF using MVVM. But unable to trigger the Icommand in the below code.If possible help me in this. Grateful if anybody can help me out.
View Code:
<Window x:Class="MVVMCalculator.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:MVVMCalculator"
mc:Ignorable="d"
Title="Calculator" Height="350" Width="300">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="85"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TextBox Text="{Binding Display, Mode=OneWay}" IsReadOnly="True" TextWrapping="Wrap"
Grid.Row="0" Background="#E2E2E2" Margin="0,10,0,0" VerticalAlignment="Top"
Height="75" Width="250" HorizontalAlignment="Center" FontSize="22" FontWeight="Bold"
TextAlignment="Right">
<TextBox.Effect>
<DropShadowEffect/>
</TextBox.Effect>
</TextBox>
<ItemsControl Grid.Row="1" ItemsSource="{Binding Buttns}" Margin="15,15,15,10">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Columns="5" Rows="4" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Content="{Binding Txt, Mode=TwoWay}" Command="{Binding Enter_number}"
FontSize="18" FontWeight="Bold" Height="50" Width="50" Background="#eef2f3"
BorderBrush="Black" BorderThickness="1.0" Name="number">
<Button.Effect>
<DropShadowEffect/>
</Button.Effect>
</Button>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
</Window>
ViewModel Code:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace MVVMCalculator
{
class ViewModel : INotifyPropertyChanged
{
Buttons btn = new Buttons();
private decimal operand1;
private decimal operand2;
private string operation;
private decimal result;
private string display;
private bool newDisplayRequired = false;
ObservableCollection<Buttons> buttns;
public ObservableCollection<Buttons> Buttns
{
get { return buttns; }
set { buttns = value; }
}
public decimal Result
{
get { return result; }
}
public decimal Operand1
{
get { return operand1; }
set { operand1 = value; }
}
public decimal Operand2
{
get { return operand2; }
set { operand2 = value; }
}
public string Operation
{
get { return operation; }
set { operation = value; }
}
public string Display
{
get { return display; }
set { display = value;
OnPropertyChanged("Display");
}
}
public ViewModel()
{
buttns = new ObservableCollection<Buttons>
{
new Buttons("1"), new Buttons("2"), new Buttons("3"),
new Buttons("C"), new Buttons("Back"), new Buttons("4"),
new Buttons("5"), new Buttons("6"), new Buttons("CE"),
new Buttons("%"), new Buttons("7"), new Buttons("8"),
new Buttons("9"), new Buttons("/"), new Buttons("*"),
new Buttons("0"), new Buttons("."), new Buttons("+"),
new Buttons("-"), new Buttons("=")
};
display = "0";
operand1 = 0;
operand2 = 0;
operation = "";
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
private ICommand enter_number;
public ICommand Enter_number
{
get
{
if(enter_number==null)
{
enter_number = new DelegateCommand<string>(MyAction, _canExecute);
}
return enter_number;
}
}
private static bool _canExecute(string button)
{
return true;
}
public void MyAction(string btn)
{
switch(btn)
{
case "C":
display = "0";
operand1 = 0;
operand2 = 0;
//operation = "";
break;
case ".":
if (!display.Contains("."))
{
Display = display + ".";
}
break;
case "Back":
if (display.Length > 1)
Display = display.Substring(0, display.Length - 1);
else Display = "0";
break;
default:
if (display == "0" || newDisplayRequired)
Display = btn;
else
Display = display + btn;
break;
}
}
}
}
Buttons Class:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MVVMCalculator
{
class Buttons:INotifyPropertyChanged
{
private string txt;
public string Txt
{
get { return txt; }
set { txt = value; }
}
public Buttons(string a)
{
txt = a;
}
public Buttons()
{
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
Xaml.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace MVVMCalculator
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new ViewModel();
}
}
}
Since the Enter_number property is defined in the ViewModel class you need to use a {RelativeSource} to be able to bind to it:
<Button Content="{Binding Txt, Mode=TwoWay}"
Command="{Binding DataContext.Enter_number, RelativeSource={RelativeSource AncestorType=ItemsControl}}"
FontSize="18" FontWeight="Bold" Height="50" Width="50" Background="#eef2f3"
BorderBrush="Black" BorderThickness="1.0" Name="number">
<Button.Effect>
<DropShadowEffect/>
</Button.Effect>
</Button>
The default DataContext of the Button is the current Buttons object in the ItemsSource collection of the ItemsControl and that's why your binding fails.
I can't seem to find simple explanation of how to set it up can some one please help out?
I've read almost every tutorial and every single one don't explain completely, my problem is that I've already written some code but I am not sure what to write in the MainWindow.xamls.cs and how to get the validation to work.
Class
public class Person : IDataErrorInfo
{
public string Fname { get; set; }
public string Lname { get; set; }
public string Error
{
get { return ""; }
}
public string this[string columnName]
{
get
{
string result = null;
if (columnName == "Fname")
{
if (string.IsNullOrEmpty(Fname))
{
result = "First name is required.";
return result;
}
string st = #"!|#|#|\$|%|\?|\>|\<|\*";
if (Regex.IsMatch(Fname, st))
{
result = "Contains invalid characters.";
return result;
}
}
if (columnName == "Lname")
{
if (string.IsNullOrEmpty(Lname))
{
result = "Cannot be empty.";
return result;
}
}
return null;
}
}
}
Xaml
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication2"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<ControlTemplate x:Key="eTemplate">
<DockPanel LastChildFill="True">
<TextBlock DockPanel.Dock="Right" Foreground="Blue" FontSize="13" Text="{Binding ElementName=adorned,Path=AdornedElement.(Validation.Errors)[0].ErrorContent}" >
</TextBlock>
<Border BorderBrush="Red" BorderThickness="2">
<AdornedElementPlaceholder x:Name="adorned"/>
</Border>
</DockPanel>
</ControlTemplate>
</Window.Resources>
<Grid>
<TextBox Height="23" Validation.ErrorTemplate="{StaticResource ResourceKey=eTemplate}" HorizontalAlignment="Left" Margin="198,71,0,0" Name="Fname" VerticalAlignment="Top" Width="120" FontSize="15">
<TextBox.Text>
<Binding Path="Fname" ValidatesOnDataErrors="True" UpdateSourceTrigger="PropertyChanged"/>
</TextBox.Text>
</TextBox>
<TextBox Height="23" Validation.ErrorTemplate="{StaticResource ResourceKey=eTemplate}" HorizontalAlignment="Left" Margin="198,130,0,0" Name="Lname" VerticalAlignment="Top" Width="120" FontSize="15">
<TextBox.Text>
<Binding Path="Lname" ValidatesOnDataErrors="True" UpdateSourceTrigger="PropertyChanged"/>
</TextBox.Text>
</TextBox>
<Label Content="FirstName" FontSize="14" Height="28" HorizontalAlignment="Left" Margin="114,71,0,0" Name="FirstName" VerticalAlignment="Top" FontFamily="Consolas" RenderTransformOrigin="0.063,0.607" Width="84"/>
<Label Content="LastName" FontSize="14" Height="28" HorizontalAlignment="Left" Margin="114,130,0,0" Name="LastName" VerticalAlignment="Top" FontFamily="Consolas" Width="79"/>
<Button x:Name="Add" Content="test" HorizontalAlignment="Left" Margin="198,186,0,0" VerticalAlignment="Top" Width="120"/>
</Grid>
</Window>
What do I do next?
Actually you've not implemented INotifyPropertyChanged interface so you property change notification is not performed. I've done some changes in your Person class as below;
public class Person : IDataErrorInfo, INotifyPropertyChanged
{
private string _fname;
private string _lname;
public String Fname
{
get { return _fname; }
set { _fname = value; OnPropertyChanged("Fname"); }
}
public String Lname
{
get { return _lname; }
set { _lname = value; OnPropertyChanged("Lname"); }
}
public string Error
{
get { return ""; }
}
public string this[string columnName]
{
get
{
string result = null;
if (columnName == "Fname")
{
if (string.IsNullOrEmpty(Fname))
{
result = "First name is required.";
return result;
}
string st = #"!|#|#|\$|%|\?|\>|\<|\*";
if (Regex.IsMatch(Fname, st))
{
result = "Contains invalid characters.";
return result;
}
}
if (columnName == "Lname")
{
if (string.IsNullOrEmpty(Lname))
{
result = "Cannot be empty.";
return result;
}
}
return null;
}
}
#region INotifyPropertyChanged implementation
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(String param)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(param));
}
}
#endregion
}
And in MainWindow.cs class, just set the DataContext as Person class;
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new Person();
}
}
I am working on WPF C#, MVVM Model. I have issue with Save_Button in View. All the things like getter, setter, RelayCommand initialization are working, just nothing happens when I click on 'Save' Buton. So it seems like Binding from View to ViewModel is not working. I am providing here only necessary files of View, ViewModel and Command part. Kindly help.
VehicalForm.xaml
<Window x:Class="Seris.VehicalForm"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<WrapPanel Orientation="Vertical" Margin="10 " >
<Label Content="Vehical No" HorizontalAlignment="Left"/>
<TextBox Name="VehicalNo_Text" Height="23" TextWrapping="Wrap" Text="TextBox" HorizontalAlignment="Left"/>
<Label Content="Model" HorizontalAlignment="Left"/>
<TextBox Name="Model_Text" Height="23" TextWrapping="Wrap" Text="TextBox" HorizontalAlignment="Left" />
<Label Content="Manufacturing Date" HorizontalAlignment="Left"/>
<DatePicker/>
<Label Content="IU No" HorizontalAlignment="Left"/>
<TextBox Height="23" Name="IUNO_Text" TextWrapping="Wrap" Text="TextBox" HorizontalAlignment="Left"/>
<Label Content="Personnel" HorizontalAlignment="Left"/>
<ComboBox Name="Personnel_Combo" HorizontalAlignment="Left" Width="116"/>
<Separator Height="20" RenderTransformOrigin="0.5,0.5" Width="16"/>
<Button Name="Save_Button" Command="{Binding SaveToList}" Content="Save" Width="66"/>
<ListView Height="294" Width="371" >
<ListView.View>
<GridView>
<GridViewColumn Header="lkj"/>
<GridViewColumn Header="lkj"/>
<GridViewColumn Header="lkj"/>
</GridView>
</ListView.View>
</ListView>
</WrapPanel>
VehicalForm.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Seris
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class VehicalForm : Window
{
public VehicalForm()
{
InitializeComponent();
}
}
}
VehicalMainViewModel.cs
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;
namespace Seris.ViewModels
{
public class VehicalMainViewModel : ObservableObject
{
ObservableCollection<VehicalModel> listItems = new ObservableCollection<VehicalModel>();
#region Getter-Setter
private string _VehicalNo;
public string VehicalNo
{
get { return _VehicalNo; }
set
{
if (value != _VehicalNo)
{
_VehicalNo = value.Trim();
OnPropertyChanged("ProductName");
}
}
}
private string _Model;
public string Model
{
get { return _Model; }
set
{
if (value != _Model)
{
_Model = value.Trim();
OnPropertyChanged("ProductName");
}
}
}
private DateTime _ManufacturingDate;
public DateTime ManufacturingDate
{
get { return _ManufacturingDate; }
set
{
if (value != _ManufacturingDate)
{
_ManufacturingDate = value;
OnPropertyChanged("ProductName");
}
}
}
private string _IUNo;
public string IUNo
{
get { return _IUNo; }
set
{
if (value != _IUNo)
{
_IUNo = value.Trim();
OnPropertyChanged("ProductName");
}
}
}
private string _PersonnelName;
public string PersonnelName
{
get { return _PersonnelName; }
set
{
if (value != _PersonnelName)
{
_PersonnelName = value.Trim();
OnPropertyChanged("ProductName");
}
}
}
#endregion
private ICommand _saveButton_Command;
public ICommand SaveButton_Command
{
get { return _saveButton_Command; }
set { _saveButton_Command = value; }
}
public void SaveToList(object o1)
{
listItems.Add(new VehicalModel(VehicalNo,Model,ManufacturingDate,IUNo,PersonnelName));
}
public void RemoveFromList()
{
}
public VehicalMainViewModel()
{
VehicalModel vm=new VehicalModel();
SaveButton_Command = new RelayCommand(new Action<object>(SaveToList));
}
}
}
RelayCommand.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
namespace Seris.Commands
{
public class RelayCommand : ICommand
{
private Action<object> _action;
public RelayCommand(Action<object> action)
{
_action = action;
}
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
_action(parameter);
}
}
}
try in XAML
<Button Name="Save_Button" Command="{Binding SaveButton_Command}" … />
You tried to Bind to the Method instead of the Command.
<Button Name="Save_Button" Command="{Binding SaveButton_Command}" />
Have you set the DataContext in on your VehicalForm-Window?
public VehicalForm()
{
InitializeComponent();
this.DataContext = new VehicalMainViewModel();
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have variable PersonnelName in class VehicleMainModel.
I want to get reference from object PersonnelObject of PersonnelMainViewModel.
When run my code following line throws Typecast exception:
PersonnelName = (bservableCollection) (PersonnelObject.Select(x => x.Name));
I don't understand how to resolve this. Even though both sides are list of string its not working. For your reference, I am attaching my both the classes here.
Please give working line for the same.
I have truncated unnecessary code for you.
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 VehicleMainViewModel _Instance;
public static VehicleMainViewModel getInstance
{
get
{
if(_Instance==null)
{
_Instance = new VehicleMainViewModel();
}
return _Instance;
}
}
private static AddVehicle _addVehicle;
public static AddVehicle addVehicle
{
get
{
return _addVehicle;
}
set
{
_addVehicle = value;
}
}
// Non-Static Variables...
// Error Components
. . .
private string _PersonnelNameSelected;
public string PersonnelNameSelected
{
get { return _PersonnelNameSelected; }
set
{
if (value == null || (!value.Equals(_PersonnelNameSelected)))
{
_PersonnelNameSelected = value;
EditText = _PersonnelNameSelected;
OnPropertyChanged("PersonnelNameSelected");
validateSpecificData(5);
}
}
}
private ObservableCollection<string> _PersonnelName;
public ObservableCollection<string> PersonnelName
{
get { return _PersonnelName; }
set
{
if (value != _PersonnelName)
{
_PersonnelName = value;
OnPropertyChanged("PersonnelName");
}
}
}
private ObservableCollection<PersonnelModel> _PersonnelObject;
public ObservableCollection<PersonnelModel> PersonnelObject
{
get { return _PersonnelObject; }
set
{
if (value != _PersonnelObject)
{
_PersonnelObject = value;
OnPropertyChanged("PersonnelObject");
}
}
}
private ObservableCollection<VehicleModel> _listItems;
public ObservableCollection<VehicleModel> ListItems
{
get { return _listItems; }
set
{
if (value == null || (!value.Equals(_listItems)))
{
_listItems = value;
}
}
}
// Other Variables
//Static Methods...
public static void showMessage(string message)
{
MessageBox.Show(message);
}
//Non-Static Methods...
. . .
public void clearAllData()
{
VehicleNo=null;
Model=null;
ManufacturingDate=null;
IUNo=null;
PersonnelNameSelected=null;
VehicleNo_Error = "";
Model_Error = "";
ManufacturingDate_Error = "";
IUNo_Error = "";
Personnel_Error= "";
}
#endregion
#region Constructors
public VehicleMainViewModel()
{
// Initialization
ListItems = new ObservableCollection<VehicleModel>();
PersonnelObject = PersonnelMainViewModel.getInstance.Personnel_List;
//This line gives error//
PersonnelName = (ObservableCollection<string>) (PersonnelObject.Select(x => x.Name));
// Setting Flags
ErrorMessage = "";
IsEnableReplaceButton = false;
// Commands Initialization
. . .
}
#endregion
}
}
PersonnelMainViewModel
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using System.ComponentModel;
using System.Windows.Markup;
using System.Windows.Data;
using System.Windows.Media.Imaging;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Windows.Documents;
using System.Windows.Controls.Primitives;
using System.Windows.Automation.Peers;
using System.Windows.Controls;
using System.Diagnostics;
using System.Security;
using System.Collections.ObjectModel;
using Seris.Models;
using Seris.Views;
using Seris.ViewModels;
using Seris.Properties;
using Seris.Commands;
namespace Seris.ViewModels
{
public class PersonnelMainViewModel :ObservableObject
{
public ObservableCollection<PersonnelModel> Personnel_List;
private ObservableCollection<PersonnelModel> Personnel_copy;
public PersonnelModel model = new PersonnelModel();
public List<string> MyString;
public ICommand EditCommand;
public ICommand AddCommand;
public bool isRemove;
public static ObservableCollection<string> PersonNameList_Updating;
private static PersonnelMainViewModel _Instance;
public static PersonnelMainViewModel getInstance
{
get
{
if (_Instance == null)
{
_Instance = new PersonnelMainViewModel();
}
return _Instance;
}
}
public PersonnelMainViewModel()
{
MyString = new List<string>();
Personnel_copy = new ObservableCollection<PersonnelModel>();
isRemove = false;
Personnel_List = new ObservableCollection<PersonnelModel>
{
new PersonnelModel{ID=Guid.NewGuid(),Name="Mr.Joe",Gender="Male",Hospital="Poly Clinic",EMPID="abc 123",Capabilities="123",Position="Assistant",Title="Test",Status="General",ICNumber="IC 123",Roles="Test"},
new PersonnelModel{ID=Guid.NewGuid(),Name="Su Su",Gender="Female",Hospital="Clementi Clinic",EMPID="abc 1234",Capabilities="1234",Position="Security",Title="Test",Status="General",ICNumber="IC 1234",Roles="Test"},
new PersonnelModel{ID=Guid.NewGuid(),Name="Ms Tan",Gender="Female",Hospital="Bishan Clinic",EMPID="abc 1235",Capabilities="1235",Position="HR",Title="Test",Status="General",ICNumber="IC 1235",Roles="Test"},
};
Personnel_copy = new ObservableCollection<PersonnelModel>
{
new PersonnelModel{ID=Guid.NewGuid(),Name="Mr.Joe",Gender="Male",Hospital="Poly Clinic",EMPID="abc 123",Capabilities="123",Position="Assistant",Title="Test",Status="General",ICNumber="IC 123",Roles="Test"},
new PersonnelModel{ID=Guid.NewGuid(),Name="Su Su",Gender="Female",Hospital="Clementi Clinic",EMPID="abc 1234",Capabilities="1234",Position="Security",Title="Test",Status="General",ICNumber="IC 1234",Roles="Test"},
new PersonnelModel{ID=Guid.NewGuid(),Name="Ms Tan",Gender="Female",Hospital="Bishan Clinic",EMPID="abc 1235",Capabilities="1235",Position="HR",Title="Test",Status="General",ICNumber="IC 1235",Roles="Test"},
};
PersonNameList_Updating = new ObservableCollection<string> (Personnel_List.Select(x => x.Name));
_hos = new ObservableCollection<string> (Personnel_List.Select(x=>x.Hospital) );
EditCommand = new RelayCommand(Edit);
AddCommand = new RelayCommand(Add);
Removecommand = new RelayCommand(Remove);
SearchCommand = new RelayCommand(search);
//string[] textList = this.FindResource("Personnel_vm") as string[];
//ICollectionView view = CollectionViewSource.GetDefaultView(textList);
//new TextSearchFilter(view, this.txtSearch);
}
. . .
#endregion
. . .
}
}
VehicleModel
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using System.Text.RegularExpressions;
using Seris.ViewModels;
namespace Seris.Models
{
public class VehicleModel : ObservableObject
{
#region Getters-Setters
private Guid? _UniqueNo;
public Guid? UniqueNo
{
get { return _UniqueNo; }
set
{
if (value != _UniqueNo)
{
_UniqueNo = value;
OnPropertyChanged("UniqueNo");
}
}
}
private string _VehicleNo;
public string VehicleNo
{
get { return _VehicleNo; }
set
{
if (value != _VehicleNo)
{
_VehicleNo = value.Trim();
OnPropertyChanged("VehicleNo");
}
}
}
private string _Model;
public string Model
{
get { return _Model; }
set
{
if (value != _Model)
{
_Model = value.Trim();
OnPropertyChanged("Model");
}
}
}
private DateTime? _ManufacturingDate;
public DateTime? ManufacturingDate
{
get { return _ManufacturingDate; }
set
{
if (value != _ManufacturingDate)
{
_ManufacturingDate = value;
OnPropertyChanged("ManufacturingDate");
}
}
}
private string _IUNo;
public string IUNo
{
get { return _IUNo; }
set
{
if (value != _IUNo)
{
_IUNo = value.Trim();
OnPropertyChanged("IUNo");
}
}
}
private string _PersonnelNameSelected;
public string PersonnelNameSelected
{
get { return _PersonnelNameSelected; }
set
{
if (value != _PersonnelNameSelected)
{
_PersonnelNameSelected = value;
OnPropertyChanged("PersonnelNameSelected");
}
}
}
#endregion
#region Methods
// Validating Forms
private void ValidateAllData(Object sender)
{
bool errorFlag=false;
if (!Validate_VehicleNo())
{
errorFlag = true;
}
if (!Validate_Model())
{
errorFlag = true;
}
if (!Validate_ManufacturingDate())
{
errorFlag = true;
}
if (!Validate_IUNo())
{
errorFlag = true;
}
if (!Validate_PersonnelName()) // For Future Enhancement
{
errorFlag = true;
}
// Personnel Remaining..........//
if (errorFlag)
throw (new Exception("Invalid Details\nClick on Help for details"));
}
public void ValidateSpecificData(Object sender, int ErrorObj)
{
bool errorFlag = false;
if (sender is VehicleMainViewModel)
{
VehicleMainViewModel senderObject = (VehicleMainViewModel)sender;
errorFlag = false;
switch(ErrorObj)
{
case 1:
if (!Validate_VehicleNo())
{
senderObject.VehicleNo_Error = "3 Caps alphabet following 4 numericals only";
errorFlag = true;
}
else
senderObject.VehicleNo_Error = "";
break;
case 2:
if (!Validate_Model())
{
senderObject.Model_Error = "Mandatory Field";
errorFlag = true;
}
else
senderObject.Model_Error = "";
break;
case 3:
if (!Validate_ManufacturingDate())
{
senderObject.ManufacturingDate_Error = "Can't be blank or future Date";
errorFlag = true;
}
else
senderObject.ManufacturingDate_Error = "";
break;
case 4:
if (!Validate_IUNo())
{
senderObject.IUNo_Error = "10 digits numerical only";
errorFlag = true;
}
else
senderObject.IUNo_Error = "";
break;
case 5:
if (!Validate_PersonnelName())
{
senderObject.Personnel_Error = "Mandatory Fvnield";
errorFlag = true;
}
else
senderObject.Personnel_Error = "";
break;
}
}
}
// To Check Regular Expressions
public bool matchRE(string stringToMatch, string regularExpression)
{
Regex regex = new Regex(#regularExpression);
Match match = regex.Match(stringToMatch);
if (match.Success)
return (true);
else
return (false);
}
#region Validate Methods
public bool Validate_VehicleNo()
{
if (VehicleNo == null || VehicleNo.Trim().Length==0)
return false;
if (matchRE(VehicleNo,"[A-Zz-z][A-Zz-z0-9]{6}"))
return true;
else
return false;
}
public bool Validate_Model()
{
if (Model == null || Model.Trim().Length==0)
return false;
if(Model!=null || Model.Length==0)
return true;
else
return false;
}
public bool Validate_ManufacturingDate()
{
if (ManufacturingDate == null || ManufacturingDate.ToString().Trim().Length == 0)
return false;
if( ManufacturingDate > DateTime.Now )
return false;
return true;
}
public bool Validate_IUNo()
{
if (IUNo == null || IUNo.Trim().Length==0)
return false;
if(matchRE(IUNo,"[0-9]{10}"))
return true;
else
return false;
}
public bool Validate_PersonnelName()
{
if (PersonnelNameSelected == null || PersonnelNameSelected.Trim().Length == 0)
return false;
else
return true;
}
#endregion
#endregion
#region Constructors
public VehicleModel(string VehicleNo, string Model, DateTime? ManufacturingDate, string IUNo, string PersonnelNameSelected)
{
this.UniqueNo = Guid.NewGuid();
this.VehicleNo = VehicleNo;
this.Model = Model;
this.ManufacturingDate = ManufacturingDate;
this.IUNo = IUNo;
this.PersonnelNameSelected = PersonnelNameSelected;
ValidateAllData(this);
}
public VehicleModel()
{
UniqueNo = null;
VehicleNo = null;
Model = null;
ManufacturingDate = null;
IUNo = null;
PersonnelNameSelected = null;
}
#endregion
}
}
AddVehicle.xaml
<Window x:Class="Seris.Views.AddVehicle"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="AddVehicle" Height="650" Width="750"
xmlns:l="clr-namespace:Seris.ViewModels">
<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="61,5,0,0" VerticalAlignment="Top" Width="84" FontWeight="Bold"/>
<Menu x:Name="AddNewPersonnel" HorizontalAlignment="Left" Height="32" Margin="10,32,-329,0" VerticalAlignment="Top" Width="611">
<MenuItem Header="Manage Vehicle >>" Margin="0" />
<MenuItem Header="Add Vehicle >>" Margin="0" />
</Menu>
<GroupBox Header="Vehicle Information" HorizontalAlignment="Left" Height="267" Margin="10,64,0,0" VerticalAlignment="Top" Width="611" FontWeight="Bold" FontSize="12"/>
<Canvas HorizontalAlignment="Left" Height="352" Margin="18,91,0,0" VerticalAlignment="Top" Width="603">
<Label Content="Vehical No" HorizontalAlignment="Left" Height="27" Width="104" Margin="10,10,0,232"/>
<TextBox Name="VehicalNo_Text" Height="27" Width="193" TextWrapping="Wrap" MaxLength="7" Text="{Binding VehicleNo, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" Margin="85,10,0,239" />
<Label Name="VehicleNoError_Label" Foreground="Red" Content="{Binding VehicleNo_Error, UpdateSourceTrigger=PropertyChanged}" Height="27" Width="275" Canvas.Left="323" Canvas.Top="10"/>
<Label Content="Model" HorizontalAlignment="Left" Height="27" Width="104" RenderTransformOrigin="0.49,-2.185" Canvas.Left="10" Canvas.Top="62"/>
<TextBox Name="Model_Text" Height="27" Width="193" TextWrapping="Wrap" MaxLength="15" Text="{Binding Model, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" Canvas.Left="85" Canvas.Top="62" />
<Label x:Name="ModelError_Label" Foreground="Red" Content="{Binding Model_Error, UpdateSourceTrigger=PropertyChanged}" Height="27" Width="275" Canvas.Left="323" Canvas.Top="62"/>
<Label Content="Manu. Date" HorizontalAlignment="Left" Height="27" Width="104" Canvas.Left="10" Canvas.Top="112"/>
<DatePicker x:Name="ManufacturingDate_DateTime" SelectedDate="{Binding ManufacturingDate, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Width="193" Height="25" Canvas.Left="85" Canvas.Top="114"/>
<Label Name="ManufacturingDateError_Label" Foreground="Red" Content="{Binding ManufacturingDate_Error, UpdateSourceTrigger=PropertyChanged}" Height="27" Width="275" Canvas.Left="323" Canvas.Top="112"/>
<Label Content="IU No" HorizontalAlignment="Left" Height="27" Width="104" Canvas.Left="10" Canvas.Top="157"/>
<TextBox Height="27" Width="193" Name="IUNO_Text" TextWrapping="Wrap" MaxLength="10" Text="{Binding IUNo, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" Canvas.Left="85" Canvas.Top="157"/>
<Label Name="IUError_Label" Foreground="Red" Content="{Binding IUNo_Error, UpdateSourceTrigger=PropertyChanged}" Height="27" Width="275" Canvas.Left="323" Canvas.Top="157"/>
<Label Content="Personnel" HorizontalAlignment="Left" Height="27" Width="104" Canvas.Left="10" Canvas.Top="198"/>
<ComboBox x:Name="Personnel_Combo" SelectedValue="{Binding PersonnelNameSelected, UpdateSourceTrigger=PropertyChanged}" ItemsSource="{Binding PersonnelName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" Height="27" Width="193" Canvas.Left="85" Canvas.Top="198"/>
<Label Name="Personnel_Label" Foreground="Red" Content="{Binding Personnel_Error, UpdateSourceTrigger=PropertyChanged}" Height="27" Width="275" Canvas.Left="318" Canvas.Top="198"/>
</Canvas>
<Label x:Name="Error_Label" Content="{Binding ErrorMessage, UpdateSourceTrigger=PropertyChanged}" Foreground="Red" HorizontalAlignment="Left" Width="236" Margin="187,345,0,200"/>
<Button Name="Help" Visibility="{Binding HelpVisibility, UpdateSourceTrigger=PropertyChanged}" Command="{Binding OpenHelpWindow_Command}" Height="50" Width="50" Margin="562,377,80,143">
<Button.DataContext>
<l:VehicleHelpViewModel />
</Button.DataContext>
<Image Height="45" Width="45" Source="../Images/help.jpg"/>
</Button>
<Button Name="Save_Button" Command="{Binding SaveButton_Command}" CommandParameter="save" Height="28" Width="81" Content="Save" Margin="265,392,346,150"/>
<TextBlock Name="Preview" Text="{Binding EditText, UpdateSourceTrigger=PropertyChanged}" Margin="13,377,542,168"/>
</Grid>
</Window>
since Select method returns an IEnumerable<T> you may perhaps do this way
IEnumerable<string> personNames = PersonnelObject.Select(x => x.Name);
PersonnelName = new ObservableCollection<string>();// optional if not initialized
foreach(string pName in personNames )
{
PersonnelName.Add(pName);
}
as the Select method returns an IEnumerable which will not propagate changes made in source collection you may perhaps solve the issue via binding itself
here is a sample for combobox
<ComboBox ItemsSource="{Binding PersonnelObject}"
DisplayMemberPath="Name" />
in above example ComboBox binds to the source collection PersonnelObject while displaying the Name property
you may perhaps revise the binding as
<ComboBox x:Name="Personnel_Combo"
SelectedValue="{Binding PersonnelNameSelected, UpdateSourceTrigger=PropertyChanged}"
ItemsSource="{Binding PersonnelObject}"
DisplayMemberPath="Name"
SelectedValuePath="Name"
HorizontalAlignment="Left"
Height="27"
Width="193"
Canvas.Left="85"
Canvas.Top="198" />
note that I have changed the ItemsSource to bind to PersonnelObject and used the SelectedValuePath and DisplayMemberPath property to display and store the correct value.
You can create ObservableCollection by initializing it like this
PersonnelName = new ObservableCollection(PersonnelObject.Select(x => x.Name));
Or
PersonnelName = new ObservableCollection<string>(PersonnelObject.Select(x => x.Name));