Calculate the textbox value based on the value of combobox ? ( wpf ) - c#

I have a small program, because I'm new, my program is to bring data from sql sever to textbox via combobox option and use the value shown in that textbox to calculate the +
I have made it to the step of putting up the data, now thanks to you to help me with the value calculation in the textbox, thank you for your help.
xaml code :
<Window x:Class="comboboxapp1.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:comboboxapp1"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.Resources>
<local:SimpleMath x:Key="MyFriends"/>
</Window.Resources>
<Grid>
<Label Content="code" HorizontalAlignment="Left" Margin="38,52,0,0"
VerticalAlignment="Top" Width="46" Height="23"/>
<Label Content="pieces" HorizontalAlignment="Left" Margin="38,126,0,0"
VerticalAlignment="Top" Width="46" Height="23"/>
<Label Content="layers" HorizontalAlignment="Left" Margin="38,196,0,0"
VerticalAlignment="Top" Width="46" Height="30"/>
<Label Content="production pieces" HorizontalAlignment="Left"
Margin="0,278,0,0" VerticalAlignment="Top" Width="108" Height="25"/>
<TextBox x:Name="txtcode"
Text="{Binding Txtcode, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
HorizontalAlignment="Left" Height="23" Margin="124,52,0,0"
TextWrapping="Wrap" VerticalAlignment="Top" Width="141"/>
<TextBox x:Name="txtpieces"
Text="{Binding Txtpieces, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
HorizontalAlignment="Left" Height="23"
Margin="124,133,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="141"/>
<TextBox x:Name="txtlayers"
Text="{Binding Txtlayers,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
HorizontalAlignment="Left" Height="23"
Margin="124,203,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="141"/>
<TextBox x:Name="txtproductionpieces"
Text="{Binding Txtproductionpieces,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
HorizontalAlignment="Left" Height="23" Margin="124,280,0,0"
TextWrapping="Wrap" VerticalAlignment="Top" Width="141"/>
<ComboBox x:Name="comboBox1" ItemsSource="{Binding Source={StaticResource MyFriends}}"
HorizontalAlignment="Left" Margin="418,52,0,0" VerticalAlignment="Top"
Width="319" Height="36" SelectionChanged="ComboBox1_SelectionChanged"/>
<TextBox x:Name="txtseccond"
Text="{Binding Txtseccond,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
HorizontalAlignment="Left" Height="23"
Margin="124,345,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="141"/>
<Label Content="seccond" HorizontalAlignment="Left" Margin="38,345,0,0"
VerticalAlignment="Top" Width="46" Height="23"/>
<TextBlock Text="{Binding A, Mode=OneWay,UpdateSourceTrigger=PropertyChanged}"
HorizontalAlignment="Left" Margin="418,133,0,0" TextWrapping="Wrap"
VerticalAlignment="Top" Height="23" Width="248"/>
<TextBox Text="{Binding No1,Mode=OneWay,UpdateSourceTrigger=PropertyChanged}"
HorizontalAlignment="Left" Height="21" Margin="426,210,0,0"
TextWrapping="Wrap" VerticalAlignment="Top" Width="303"/>
</Grid>
</Window>
C# code:
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;
using System.Data.SqlClient;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace comboboxapp1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public SimpleMath Formular { get; set; }
public object SelectedValue { get; private set; }
public MainWindow()
{
Formular = new SimpleMath()
{
Txtcode = 0,
Txtpieces = 0,
Txtlayers = 0,
Txtproductionpieces = 0,
Txtseccond = 0,
};
InitializeComponent();
DataContext = Formular;
Fillcombobox();
}
private void MainWindow_Load(object sender, EventArgs e)
{
}
public void Fillcombobox()
{
SqlConnection con = new SqlConnection("Data Source=LEAN-22\\SQLEXPRESS;Initial
Catalog=LUAT;Integrated Security=True");
string sql = " select * from comboboxnew ";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader myreader;
try
{
con.Open();
myreader = cmd.ExecuteReader();
while (myreader.Read())
{
string sname = myreader.GetInt32(0).ToString();
comboBox1.Items.Add(sname);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public class SimpleMath : INotifyPropertyChanged
{
private int no1;
public int No1
{
get { return no1; }
set
{
no1 = value;
OnPropertyChanged("No1");
OnPropertyChanged("A");
}
}
private int txtcode;
public int Txtcode
{
get { return txtcode; }
set
{
txtcode = value;
OnPropertyChanged("Txtcode");
OnPropertyChanged("A");
}
}
private int txtpieces;
public int Txtpieces
{
get { return txtpieces; }
set
{
txtpieces = value;
OnPropertyChanged("Txtcode");
OnPropertyChanged("A");
}
}
private int txtlayers;
public int Txtlayers
{
get { return txtlayers; }
set
{
txtlayers = value;
OnPropertyChanged("Txtlayers");
OnPropertyChanged("A");
}
}
private int txtproductionpieces;
public int Txtproductionpieces
{
get { return txtproductionpieces; }
set
{
txtproductionpieces = value;
OnPropertyChanged("Txtproductionpieces");
OnPropertyChanged("A");
}
}
private int txtseccond;
public int Txtseccond
{
get { return txtseccond; }
set
{
txtseccond = value;
OnPropertyChanged("Txtseccond");
OnPropertyChanged("A");
}
}
public double A => No1;
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName()] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
private void ComboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=LEAN-22\\SQLEXPRESS;Initial
Catalog=LUAT;Integrated Security=True");
// string sql = " select * from comboboxnew where code = '" + comboBox1.Text+ "';";
string sql = " select * from comboboxnew where code = '" + comboBox1.SelectedItem +
"';";
//Console.WriteLine(comboBox1.Text);
//MessageBox.Show(comboBox1.Text);
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader myreader;
try
{
con.Open();
myreader = cmd.ExecuteReader();
while (myreader.Read())
{
string code = myreader.GetInt32(0).ToString();
string pieces = myreader.GetInt32(1).ToString();
string layers = myreader.GetInt32(2).ToString();
string productionpieces = myreader.GetInt32(3).ToString();
string seccond = myreader.GetInt32(4).ToString();
txtcode.Text = code;
//txtcode.Text =SelectedValue;
txtpieces.Text = pieces;
//txtpieces.Text = "New value";
txtlayers.Text = layers;
//txtlayers.Text = "New value";
txtproductionpieces.Text = productionpieces;
//txtproductionpieces.Text = "New value";
txtseccond.Text = seccond;
//txtseccond.Text = "New value";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}

From what I understand, you simply want to sum those five values into the TextBox, right?
If so, you can do that multiple ways...
One:
Have a property in the SimpleMath class that is the sum of the other values, and bind that to the TextBox. You would have to update the sum property whenever any of those five other ones updates.
Two:
You could use the IMultiValueConverter to sum the values without having any more properties in the SimpleMath class. It's done like this:
You create a class that implements the IMultiValueConverter inteface
public class SumConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
return values.Cast<int>()?.Sum()?.ToString();
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
return null;
}
}
And use it in XAML like this
<TextBox>
<TextBox.Resources>
<local:SumConverter x:Key="SumConverter"/>
</TextBox.Resources>
<TextBox.Text>
<MultiBinding Converter="{StaticResource SumConverter}">
<Binding Path="Text" ElementName="OtherTextBox1" />
<Binding Path="Text" ElementName="OtherTextBox2" />
<Binding Path="Text" ElementName="OtherTextBox3" />
<Binding Path="Text" ElementName="OtherTextBox4" />
<Binding Path="Text" ElementName="OtherTextBox5" />
</MultiBinding>
</TextBox.Text>
</Control>
Hope this helps
EDIT
I've made a test project to show you the full code for both of my suggested solutions, here it is:
Solution one
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows;
namespace StackOverflowTest
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new SimpleMath();
}
}
public class SimpleMath : INotifyPropertyChanged
{
private int _numberOne;
public int NumberOne
{
get => _numberOne;
set
{
_numberOne = value;
OnPropertyChanged();
CalculateSum();
}
}
private int _numberTwo;
public int NumberTwo
{
get => _numberTwo;
set
{
_numberTwo = value;
OnPropertyChanged();
CalculateSum();
}
}
private int _numberThree;
public int NumberThree
{
get => _numberThree;
set
{
_numberThree = value;
OnPropertyChanged();
CalculateSum();
}
}
private int _numberSum;
public int NumberSum
{
get => _numberSum;
set
{
_numberSum = value;
OnPropertyChanged();
}
}
private void CalculateSum()
{
NumberSum = NumberOne + NumberTwo + NumberThree;
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName()] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
<Window x:Class="StackOverflowTest.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:StackOverflowTest"
mc:Ignorable="d"
Title="MainWindow" Height="200" Width="200">
<StackPanel>
<TextBox x:Name="TxtOne" HorizontalAlignment="Stretch" Text="{Binding NumberOne}" Margin="10,10,10,0"/>
<TextBox x:Name="TxtTwo" HorizontalAlignment="Stretch" Text="{Binding NumberTwo}" Margin="10,10,10,0"/>
<TextBox x:Name="TxtThree" HorizontalAlignment="Stretch" Text="{Binding NumberThree}" Margin="10,10,10,0"/>
<TextBlock HorizontalAlignment="Center" Text="{Binding NumberSum}" Margin="10,10,10,0"/>
</StackPanel>
</Window>
Solution two
using System;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Data;
using System.Collections.Generic;
namespace StackOverflowTest
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new SimpleMath();
}
}
public class SimpleMath : INotifyPropertyChanged
{
private int _numberOne;
public int NumberOne
{
get => _numberOne;
set
{
_numberOne = value;
OnPropertyChanged();
}
}
private int _numberTwo;
public int NumberTwo
{
get => _numberTwo;
set
{
_numberTwo = value;
OnPropertyChanged();
}
}
private int _numberThree;
public int NumberThree
{
get => _numberThree;
set
{
_numberThree = value;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName()] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class SumConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
var numbers = new List<int>();
foreach (var item in values)
{
if(item is string stringValue)
{
try
{
numbers.Add(System.Convert.ToInt32(stringValue));
}
catch (Exception)
{
Console.WriteLine("Oops, not a number...");
}
}
}
return numbers.Sum().ToString();
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
return null;
}
}
}
<Window x:Class="StackOverflowTest.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:StackOverflowTest"
mc:Ignorable="d"
Title="MainWindow" Height="200" Width="200">
<StackPanel>
<TextBox x:Name="TxtOne" HorizontalAlignment="Stretch" Text="{Binding NumberOne}" Margin="10,10,10,0"/>
<TextBox x:Name="TxtTwo" HorizontalAlignment="Stretch" Text="{Binding NumberTwo}" Margin="10,10,10,0"/>
<TextBox x:Name="TxtThree" HorizontalAlignment="Stretch" Text="{Binding NumberThree}" Margin="10,10,10,0"/>
<TextBlock HorizontalAlignment="Center" Margin="10,10,10,0">
<TextBlock.Resources>
<local:SumConverter x:Key="SumConverter"/>
</TextBlock.Resources>
<TextBlock.Text>
<MultiBinding Converter="{StaticResource SumConverter}">
<Binding Path="Text" ElementName="TxtOne" />
<Binding Path="Text" ElementName="TxtTwo" />
<Binding Path="Text" ElementName="TxtThree" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</StackPanel>
</Window>
Here's how it looks

Related

The name MainViewModel does not exist in the namespace "clr-namespace:LINQ3_Test_aus_LINQ2"

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.

Unable to use MVVM/binding correctly in the below code and having issues with Icommand property

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.

WPF IDataErrorInfo issue

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();
}
}

Binding is not working in WPF MVVM C#

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();
}

RunTime Exception while Casting Variables/Objects [closed]

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));

Categories