Windows 10 and wpf bidning - wpf

does anyone knows if there is any issue binding data using windows 10 and visual studio 10 WPF project?
it should be very simple code line and i don't see any reason why the data is not binding
the data is biding in the xaml so i dont see other problem
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;
using WpfApplication2.ViewModel;
namespace WpfApplication2
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
WpfApplication2.MainWindow window = new MainWindow();
UserViewModel VM = new UserViewModel();
window.DataContext = VM;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
namespace WpfApplication2.ViewModel
{
class UserViewModel
{
private IList<User> _UsersList;
public UserViewModel()
{
_UsersList = new List<User>
{
new User{UserId = 1,FirstName="Raj",LastName="Beniwal",City="Delhi",State="DEL",Country="INDIA"},
new User{UserId=2,FirstName="Mark",LastName="henry",City="New York", State="NY", Country="USA"},
new User{UserId=3,FirstName="Mahesh",LastName="Chand",City="Philadelphia", State="PHL", Country="USA"},
new User{UserId=4,FirstName="Vikash",LastName="Nanda",City="Noida", State="UP", Country="INDIA"},
new User{UserId=5,FirstName="Harsh",LastName="Kumar",City="Ghaziabad", State="UP", Country="INDIA"},
new User{UserId=6,FirstName="Reetesh",LastName="Tomar",City="Mumbai", State="MP", Country="INDIA"},
new User{UserId=7,FirstName="Deven",LastName="Verma",City="Palwal", State="HP", Country="INDIA"},
new User{UserId=8,FirstName="Ravi",LastName="Taneja",City="Delhi", State="DEL", Country="INDIA"}
};
}
public IList<User> Users
{
get { return _UsersList; }
set { _UsersList = value; }
}
private ICommand mUpdater;
public ICommand UpdateCommand
{
get
{
if (mUpdater == null)
mUpdater = new Updater();
return mUpdater;
}
set
{
mUpdater = value;
}
}
private class Updater : ICommand
{
#region ICommand Members
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
}
#endregion
}
}
}
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="485" Width="525">
<Grid Margin="0,0,0,20">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<ListView Name="UserGrid" Grid.Row="1" Margin="4,178,12,13" ItemsSource="{Binding Users}" >
<ListView.View>
<GridView x:Name="grdTest">
<GridViewColumn Header="UserId" DisplayMemberBinding="{Binding UserId}" Width="50"/>
<GridViewColumn Header="First Name" DisplayMemberBinding="{Binding FirstName}" Width="80" />
<GridViewColumn Header="Last Name" DisplayMemberBinding="{Binding LastName}" Width="100" />
<GridViewColumn Header="City" DisplayMemberBinding="{Binding City}" Width="80" />
<GridViewColumn Header="State" DisplayMemberBinding="{Binding State}" Width="80" />
<GridViewColumn Header="Country" DisplayMemberBinding="{Binding Country}" Width="100" />
</GridView>
</ListView.View>
</ListView>
<TextBox Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="80,7,0,0" Name="txtUserId" VerticalAlignment="Top" Width="178" Text="{Binding ElementName=UserGrid,Path=SelectedItem.UserId}" />
<TextBox Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="80,35,0,0" Name="txtFirstName" VerticalAlignment="Top" Width="178" Text="{Binding ElementName=UserGrid,Path=SelectedItem.FirstName}" />
<TextBox Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="80,62,0,0" Name="txtLastName" VerticalAlignment="Top" Width="178" Text="{Binding ElementName=UserGrid,Path=SelectedItem.LastName}" />
<Label Content="UserId" Grid.Row="1" HorizontalAlignment="Left" Margin="12,12,0,274" Name="label1" />
<Label Content="Last Name" Grid.Row="1" Height="28" HorizontalAlignment="Left" Margin="12,60,0,0" Name="label2" VerticalAlignment="Top" />
<Label Content="First Name" Grid.Row="1" Height="28" HorizontalAlignment="Left" Margin="12,35,0,0" Name="label3" VerticalAlignment="Top" />
<Button Content="Update" Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="310,40,0,0" Name="btnUpdate"
VerticalAlignment="Top" Width="141"
Command="{Binding Path=UpdateCommad}" />
<TextBox Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="80,143,0,0" x:Name="txtCity" VerticalAlignment="Top" Width="178" Text="{Binding SelectedItem.City, ElementName=UserGrid}" />
<Label Content="Country" Grid.Row="1" Height="28" HorizontalAlignment="Left" Margin="12,141,0,0" x:Name="label2_Copy" VerticalAlignment="Top" />
<TextBox Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="80,88,0,0" x:Name="txtCountry" VerticalAlignment="Top" Width="178" Text="{Binding SelectedItem.Country, ElementName=UserGrid}" />
<Label Content="City" Grid.Row="1" Height="28" HorizontalAlignment="Left" Margin="12,86,0,0" x:Name="label2_Copy1" VerticalAlignment="Top" />
<TextBox Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="80,115,0,0" x:Name="txtSTate" VerticalAlignment="Top" Width="178" Text="{Binding SelectedItem.State, ElementName=UserGrid}" />
<Label Content="State" Grid.Row="1" Height="28" HorizontalAlignment="Left" Margin="12,113,0,0" x:Name="label2_Copy2" VerticalAlignment="Top" />
</Grid>
</Window>

Use ObservableCollection instead of List:
private ObservableCollection<User> _users = new ObservableCollection<User>();
public ObservableCollection<User> Users
{
get { return _users; }
set
{
_users= value;
OnPropertyChanged();
}
}

As you are using 'IList' the problem is that the list initially is empty when binded to UI. The bindings take place when InitializeComponent() is called. Hence the ItemsSource property has to be updated.
UserGrid.ItemsSource = Users;
Adding the above line will solve your problem.
It is better to use ObservableCollection instead of List, as it automatically updates the UI when any change has been made on the binded value.

Related

how to update listitem(observableObject) in Listview(observerableCollection) in WPF

I have a collection of instruments, and I'd like to configure each of them after I add them to a list
Currently this instrument is defined as a class inherited from ObservableObject, and stored in an ObservableCollection, shown as a Listview with a datatemplate of instrument details.
Now I can add/delete an instrument. but when I try to update instrument details(e.g. names, type). it is not update to instrument class property.
I'm using CommunityToolkit.Mvvm, I tested that it will work if I just put an instrument details in textbox as the direct element in the mainwindow, but not work as listviewitem.
So does it mean that I can't put observableObject under another observableObject/ObserverbaleCollection?
<ListView x:Name="ListView_Instr"
ItemsSource="{Binding InstrumentConfigs, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
SelectedItem="{Binding SelectInstrumentConfig, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
Padding="5,5,5,5" Grid.Row="0">
<ListView.ItemTemplate>
<DataTemplate>
<Grid Width="{Binding Width, ElementName=ListView_Instr}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="2*"/>
<ColumnDefinition Width="3*"/>
<ColumnDefinition Width="3*"/>
<ColumnDefinition Width="2*"/>
</Grid.ColumnDefinitions>
<CheckBox x:Name="CheckBox_InstrChecked" Grid.Column="0"/>
<StackPanel Orientation="Horizontal" Grid.Column="1">
<Label Content="Type"/>
<ComboBox x:Name="ComboBox_InstrType" ItemsSource="{Binding InstrTypes, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>
</StackPanel>
<StackPanel Orientation="Horizontal" Grid.Column="2">
<Label Content="Name"/>
<TextBox x:Name="TextBox_InstrName" Text="{Binding InstrName, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" />
</StackPanel>
<StackPanel Orientation="Horizontal" Grid.Column="3">
<Label Content="Addr"/>
<TextBox x:Name="TextBox_InstrAddr" Text="{Binding InstrAddr, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" />
</StackPanel>
<StackPanel Orientation="Horizontal" Grid.Column="4">
<Label Content="Interface"/>
<ComboBox x:Name="ComboBox_InstrInterface" ItemsSource="{Binding InstrInterfaceTypes, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>
</StackPanel>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Any detail I missed when using Observable?
Thanks
The following way should work.
Instrument.cs
using CommunityToolkit.Mvvm.ComponentModel;
namespace wpf_binding
{
[INotifyPropertyChanged]
public partial class Instrument
{
[ObservableProperty]
private string name;
[ObservableProperty]
private string description;
partial void OnNameChanged(string value)
{
System.Console.WriteLine($"Name changed: {Name}");
}
partial void OnDescriptionChanged(string value)
{
System.Console.WriteLine($"Description changed: {Description}");
}
}
}
ViewModel.cs
using CommunityToolkit.Mvvm.ComponentModel;
using System.Collections.ObjectModel;
namespace wpf_binding
{
[INotifyPropertyChanged]
public partial class ViewModel
{
[ObservableProperty]
private ObservableCollection<Instrument> instruments;
[ObservableProperty]
private Instrument selectedItem;
public ViewModel()
{
Instruments = new ObservableCollection<Instrument>()
{
new Instrument() { Name = "Item 1", Description = "Desc 1" },
new Instrument() { Name = "Item 2", Description = "Desc 2" }
};
}
}
}
MainWindow.xaml
<Window x:Class="wpf_binding.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:wpf_binding"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<StackPanel Orientation="Vertical">
<ListView ItemsSource="{Binding Instruments}" SelectedItem="{Binding SelectedItem}">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBox Text="{Binding Name, Mode=TwoWay}"/>
<TextBox Text="{Binding Description, Mode=TwoWay}"/>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<StackPanel Orientation="Vertical">
<StackPanel Orientation="Horizontal">
<TextBlock Text="Name:"/>
<TextBlock Text="{Binding SelectedItem.Name}"/>
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Description:"/>
<TextBlock Text="{Binding SelectedItem.Description}"/>
</StackPanel>
</StackPanel>
</StackPanel>
</Window>
MainWindow.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 wpf_binding
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new ViewModel();
}
}
}

validation in MVVM by using annotaions?

I am new to WPF I need to validate those properties mentioned in my ViewModel how could I do it in a simplest way?
can anybody help? any way I can do it in MVVM.
I do have tried with the XAML template but there also I couldn't make it with multiple controls.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using FeedbackForm.Model;
using System.Windows.Input;
using System.Windows;
using System.Windows.Controls;
using MySql.Data.MySqlClient;
using System.ComponentModel.DataAnnotations;
namespace FeedbackForm.ViewModel
{
class MainViewModel:INotifyPropertyChanged
{
static int i = 1;
public data domObject;
public ICommand _SubmitCmd{get;set;}
public ICommand _ResetCmd{get;set;}
public Connection con;
public MainViewModel()
{
domObject= new data();
_SubmitCmd = new DelegateComand.DelegateCommand(OnSubmit);
_ResetCmd = new DelegateComand.DelegateCommand(OnReset);
}
public class EmailValidationAttribute : RegularExpressionAttribute
{
public EmailValidationAttribute()
: base(#"^([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+#((((([a-zA-Z0-9]{1}[a-zA-Z0-9\-]{0,62}[a-zA-Z0-9]{1})|[a-zA-Z])\.)+[a-zA-Z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$")
{
}
}
public string Fname
{
get
{return domObject.fname ;}
set
{
domObject.fname =value ;
OnPropertyChanged("Fname");
}
}
public string Lname
{
get
{ return domObject.lname; }
set
{
domObject.lname = value;
OnPropertyChanged("Lname");
}
}
public bool Gender
{
get
{ return domObject.gender; }
set
{
domObject.gender = value;
OnPropertyChanged("Gender");
}
}
public decimal Contact
{
get
{ return domObject.contact ; }
set
{
domObject.contact = value;
OnPropertyChanged("Contact");
// try
// {
// //int.Parse(Contact);
// Convert.ToInt32(Contact);
// }
// catch (Exception ex)
//{
// throw new ApplicationException("Invalid Number");
//}
}
}
[EmailValidation(ErrorMessage = "Not in proper format")]
public string Email
{
get
{ return domObject.email; }
set
{
domObject.email = value;
OnPropertyChanged("Email");
}
}
public string Address
{
get
{ return domObject.address ; }
set
{
domObject.address = value;
OnPropertyChanged("Address");
}
}
public string Query
{
get
{ return domObject.query ; }
set
{
domObject.query = value;
OnPropertyChanged("Query");
}
}
public string Comment
{
get
{ return domObject.comment ; }
set
{
domObject.comment = value;
OnPropertyChanged("Comment");
}
}
private void OnReset(object obj)
{
ResetAll(this );
}
private void OnSubmit(object obj)
{ char g;
con = new Connection();
try{
if (domObject.gender == false)
{
g = 'M';
}
else
{
g = 'F';
}
con.command.CommandText = "Insert into tblfeedback(fname,lname,gender,email,contact_no,Address) values('" + domObject.fname + "','" + domObject.lname + "','" + g + "','" + domObject.email + "','" + domObject.contact + "','" + domObject.address + "')";
con.command.ExecuteNonQuery();
con.command.CommandText = "Insert into comment (query,comment,date)values('" + domObject.query + "','" + domObject.comment + "','" +( DateTime.Today.ToShortDateString().ToString())+ "')";
con.command.ExecuteNonQuery();
i++;
ResetAll(this);
}
catch (Exception ex)
{
MessageBox.Show("ERROR" + ex);
}
}
public void ResetAll(object obj)
{
Fname = String.Empty;
Lname = String.Empty;
Gender = false;
Contact = 0;
Address = String.Empty;
Query = String.Empty;
Comment = String.Empty;
Email = String.Empty;
}
#region INotifyPropertyChanged Members
/// <summary>
/// Event to which the view's controls will subscribe.
/// This will enable them to refresh themselves when the binded property changes provided you fire this event.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// When property is changed call this method to fire the PropertyChanged Event
/// </summary>
/// <param name="propertyName"></param>
public void OnPropertyChanged(string propertyName)
{
//Fire the PropertyChanged event in case somebody subscribed to it
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
}
Following Xaml contains the Template which I used to validate contact property but I want to validate my Email by any means. I am new to WPF so I just want to know how can I use Regular Expression or anything to do that???
<Window x:Class="FeedbackForm.View.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="490.602" Width="549.249">
<Window.Resources>
<ControlTemplate x:Key="ValidationTemplate">
<DockPanel LastChildFill="True">
<TextBlock DockPanel.Dock="Right"
Foreground="Red"
FontSize="12pt" Text="{Binding [0].ErrorContent}">
</TextBlock>
<Border BorderBrush="Red" BorderThickness="1">
<AdornedElementPlaceholder />
</Border>
</DockPanel>
</ControlTemplate>
</Window.Resources>
<DockPanel Background="Aquamarine">
<Grid Margin="0,25,0,-25">
<Grid.RowDefinitions>
<RowDefinition Height="51*" />
<RowDefinition Height="47*" />
<RowDefinition Height="44*" />
<RowDefinition Height="48*" />
<RowDefinition Height="61*" />
<RowDefinition Height="74*" />
<RowDefinition Height="64*" />
<RowDefinition Height="72*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions >
<ColumnDefinition Width="Auto" MinWidth="130"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Label Content="First Name" Grid.Column="0" HorizontalAlignment="Left" Margin="10,4,0,0" VerticalAlignment="Top" Height="26" Width="67"/>
<Label Content="Gender" Grid.Column="0" HorizontalAlignment="Left" Margin="10,2,0,0" Grid.Row="1" VerticalAlignment="Top" Height="26" Width="49"/>
<Label Content="E-mail" Grid.Column="0" HorizontalAlignment="Left" Margin="10,5,0,0" Grid.Row="2" VerticalAlignment="Top" Height="26" Width="43"/>
<Label Content="Contact" Grid.Column="0" HorizontalAlignment="Left" Margin="11,5,0,0" Grid.Row="3" VerticalAlignment="Top" Height="26" Width="51"/>
<Label Content="Address" Grid.Column="0" HorizontalAlignment="Left" Margin="9,4,0,0" Grid.Row="4" VerticalAlignment="Top" Height="26" Width="53"/>
<Label Content="Query" Grid.Column="0" HorizontalAlignment="Left" Margin="10,3,0,0" Grid.Row="5" VerticalAlignment="Top" Height="26" Width="42"/>
<Label Content="Comment" Grid.Column="0" HorizontalAlignment="Left" Margin="10,3,0,0" Grid.Row="6" VerticalAlignment="Top" Height="26" Width="62"/>
<Label Content="Last Name" Grid.Column="1" HorizontalAlignment="Left" Margin="162,7,0,0" VerticalAlignment="Top" Height="26" Width="66"/>
<Button x:Name="submit" Command="{Binding Path=_SubmitCmd}" Content="Submit" HorizontalAlignment="Left" Margin="17,10,0,0" Grid.Row="7" VerticalAlignment="Top" Width="75" Height="22" Grid.Column="1" Click="submit_Click"/>
<Button x:Name="reset" Content="Reset" HorizontalAlignment="Left" Margin="162,10,0,0" Grid.Row="7" VerticalAlignment="Top" Width="75" Grid.Column="1" Height="22" Command="{Binding _ResetCmd}"/>
<TextBox x:Name="txtfname" HorizontalAlignment="Left" Height="23" Margin="10,10,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120" Grid.Column="1" Text="{Binding Fname}" TabIndex="1"/>
<TextBox x:Name="txtlname" HorizontalAlignment="Left" Height="23" Margin="262,10,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120" Grid.Column="1" TabIndex="2">
<Binding Path="Lname"></Binding>
</TextBox>
<RadioButton x:Name="rdfemale" Content="FEMALE" GroupName="grp1" IsChecked="{Binding Gender, Mode=TwoWay}" HorizontalAlignment="Left" Margin="130,12,0,0" Grid.Row="1" VerticalAlignment="Top" Grid.Column="1" Height="16" Width="82"/>
<RadioButton x:Name="rdmale" Content="MALE" GroupName="grp1" HorizontalAlignment="Left" Margin="10,12,0,0" Grid.Row="1" VerticalAlignment="Top" Grid.Column="1" Height="16" Width="82" />
<TextBox x:Name="txtemail" HorizontalAlignment="Left" Height="23" Margin="10,10,0,0" Grid.Row="2" TextWrapping="Wrap" VerticalAlignment="Top" Width="191" Grid.Column="1" TabIndex="3">
<TextBox.Text>
<Binding Path="Email" Mode="TwoWay">
</Binding>
</TextBox.Text>
</TextBox>
<TextBox x:Name="txtcontact" Validation.ErrorTemplate="{StaticResource ValidationTemplate}" HorizontalAlignment="Left" Height="23" Margin="10,10,0,0" Grid.Row="3" TextWrapping="Wrap" VerticalAlignment="Top" Width="191" Grid.Column="1" TabIndex="4">
<TextBox.Text>
<Binding Path="Contact" UpdateSourceTrigger="LostFocus">
<Binding.ValidationRules>
<ExceptionValidationRule></ExceptionValidationRule>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
<RichTextBox x:Name="rtxtquery" SpellCheck.IsEnabled="True" HorizontalAlignment="Left" Height="38" Margin="10,23,0,0" Grid.Row="5" VerticalAlignment="Top" Width="276" RenderTransformOrigin="0.4,0.413" Grid.Column="1" TabIndex="6" >
<FlowDocument>
<Paragraph>
<Run Text="{Binding Query}"/>
</Paragraph>
</FlowDocument>
</RichTextBox>
<RichTextBox x:Name="rtxtadd" HorizontalAlignment="Left" Height="38" Margin="10,10,0,0" Grid.Row="4" VerticalAlignment="Top" Width="276" RenderTransformOrigin="0.4,0.413" Grid.Column="1" TabIndex="5">
<FlowDocument>
<Paragraph>
<Run Text="{Binding Address}"/>
</Paragraph>
</FlowDocument>
</RichTextBox>
<RichTextBox Grid.Column="1" SpellCheck.IsEnabled="True" HorizontalAlignment="Left" Height="44" Margin="10,10,0,0" Grid.Row="6" VerticalAlignment="Top" Width="276" TabIndex="7">
<FlowDocument>
<Paragraph>
<Run Text="{Binding Comment}"/>
</Paragraph>
</FlowDocument>
</RichTextBox>
</Grid>
</DockPanel>
</Window>
Creating Validation Rule or Using IDataErrorInfo
http://www.codeproject.com/Tips/784331/WPF-MVVM-Validation-ViewModel-using-IDataErrorInfo

How to insert paaswordbox value into database table?

I used PasswordHelper class to bind passwordbox with viewmodel but still property field is null at submit time. i tried with debugger but property doesn't getting value.
XAML Code..
<Page x:Class="ChatApp.View.Register"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:se="http://schemas.microsoft.com/expression/2010/interactions"
xmlns:vm="clr-namespace:ChatApp.ViewModel"
xmlns:w="clr-namespace:ChatApp"
mc:Ignorable="d"
d:DesignHeight="347" d:DesignWidth="350"
Title="Register">
<Page.DataContext>
<vm:RegisterViewModel></vm:RegisterViewModel>
</Page.DataContext>
<Grid Height="317">
<Grid.RowDefinitions>
<RowDefinition Height="30" />
<RowDefinition Height="30" />
<RowDefinition Height="30" />
<RowDefinition Height="30" />
<RowDefinition Height="30" />
<RowDefinition Height="30" />
<RowDefinition Height="63" />
<RowDefinition Height="32" />
<RowDefinition Height="42*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="112*"/>
<ColumnDefinition Width="188*" />
</Grid.ColumnDefinitions>
<Label Content="User ID :" Grid.Row="1" Height="28" HorizontalAlignment="Left" Margin="12,0,0,0" Name="label1" VerticalAlignment="Top" />
<Label Content="Password :" Grid.Row="2" Height="28" HorizontalAlignment="Left" Margin="12,2,0,0" Name="label2" VerticalAlignment="Top" />
<Label Content="Name" Grid.Row="3" Height="28" HorizontalAlignment="Left" Margin="12,0,0,0" Name="label3" VerticalAlignment="Top" />
<Label Content="Email ID :" Grid.Row="4" Height="28" HorizontalAlignment="Left" Margin="12,2,0,0" Name="label4" VerticalAlignment="Top" />
<Label Content="Contact No :" Grid.Row="5" Height="29" HorizontalAlignment="Left" Margin="12,1,0,0" Name="label5" VerticalAlignment="Top" />
<Label Content="Address :" Grid.Row="6" Height="28" HorizontalAlignment="Left" Margin="12,0,0,0" Name="label6" VerticalAlignment="Top" />
<Label Content="Designation :" Grid.Row="7" Height="28" HorizontalAlignment="Left" Margin="12,0,0,0" Name="label7" VerticalAlignment="Top" />
<TextBox Text="{Binding userID}" Grid.Column="1" Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="0,3,0,0" Name="txtID" VerticalAlignment="Top" Width="207" />
<TextBox Grid.Column="1" Text="{Binding password}" Grid.Row="2" Height="23" HorizontalAlignment="Left" Name="txtpassword" VerticalAlignment="Top" Width="207" Margin="0,2,0,0" />
<TextBox Text="{Binding name}" Grid.Column="1" Grid.Row="3" Height="23" HorizontalAlignment="Left" Name="txtName" VerticalAlignment="Top" Width="207" Margin="0,2,0,0" />
<TextBox Text="{Binding emailID}" Grid.Column="1" Grid.Row="4" Height="23" HorizontalAlignment="Left" Margin="0,2,12,0" Name="txtEmail" VerticalAlignment="Top" Width="207" />
<TextBox Text="{Binding contact}" Grid.Column="1" Grid.Row="5" Height="23" HorizontalAlignment="Left" Name="txtContact" VerticalAlignment="Top" Width="207" Margin="0,2,0,0" />
<TextBox Text="{Binding address}" Grid.Column="1" Grid.Row="6" Height="56" HorizontalAlignment="Left" Margin="0,2,0,0" Name="txtAddress" VerticalAlignment="Top" Width="207" TextWrapping="Wrap" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto" />
<TextBox Text="{Binding designation}" Grid.Column="1" Grid.Row="7" Height="23" HorizontalAlignment="Left" Name="txtDesignation" VerticalAlignment="Top" Width="207" Margin="0,1,0,0" />
<TextBlock Height="28" HorizontalAlignment="Left" Margin="49,1,0,0" Name="textBlock1" Text="New Registration" VerticalAlignment="Top" Width="169" Grid.ColumnSpan="2" FontWeight="Bold" FontSize="20" />
<Button Content="Register" Grid.Row="8" Height="23" HorizontalAlignment="Left" Margin="33,5,0,0" Name="btnSubmit" VerticalAlignment="Top" Width="75" Grid.Column="1">
<i:Interaction.Triggers>
<i:EventTrigger SourceObject="{Binding ElementName=btnSubmit}" EventName="Click">
<se:CallMethodAction MethodName="SubmitDetail" TargetObject="{Binding DataContext, ElementName=btnSubmit}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
</Grid>
here is my password helper class.
public static class PasswordHelper
{
public static readonly DependencyProperty PasswordProperty =
DependencyProperty.RegisterAttached("Password",
typeof(string), typeof(PasswordHelper),
new FrameworkPropertyMetadata(string.Empty, OnPasswordPropertyChanged));
public static readonly DependencyProperty AttachProperty =
DependencyProperty.RegisterAttached("Attach",
typeof(bool), typeof(PasswordHelper), new PropertyMetadata(false, Attach));
private static readonly DependencyProperty IsUpdatingProperty =
DependencyProperty.RegisterAttached("IsUpdating", typeof(bool),
typeof(PasswordHelper));
public static void SetAttach(DependencyObject dp, bool value)
{
dp.SetValue(AttachProperty, value);
}
public static bool GetAttach(DependencyObject dp)
{
return (bool)dp.GetValue(AttachProperty);
}
public static string GetPassword(DependencyObject dp)
{
return (string)dp.GetValue(PasswordProperty);
}
public static void SetPassword(DependencyObject dp, string value)
{
dp.SetValue(PasswordProperty, value);
}
private static bool GetIsUpdating(DependencyObject dp)
{
return (bool)dp.GetValue(IsUpdatingProperty);
}
private static void SetIsUpdating(DependencyObject dp, bool value)
{
dp.SetValue(IsUpdatingProperty, value);
}
private static void OnPasswordPropertyChanged(DependencyObject sender,
DependencyPropertyChangedEventArgs e)
{
PasswordBox passwordBox = sender as PasswordBox;
passwordBox.PasswordChanged -= PasswordChanged;
if (!(bool)GetIsUpdating(passwordBox))
{
passwordBox.Password = (string)e.NewValue;
}
passwordBox.PasswordChanged += PasswordChanged;
}
private static void Attach(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
PasswordBox passwordBox = sender as PasswordBox;
if (passwordBox == null)
return;
if ((bool)e.OldValue)
{
passwordBox.PasswordChanged -= PasswordChanged;
}
if ((bool)e.NewValue)
{
passwordBox.PasswordChanged += PasswordChanged;
}
}
private static void PasswordChanged(object sender, RoutedEventArgs e)
{
PasswordBox passwordBox = sender as PasswordBox;
SetIsUpdating(passwordBox, true);
SetPassword(passwordBox, passwordBox.Password);
SetIsUpdating(passwordBox, false);
}
}
I see two problems with your code:
1.
XAML is case sensitive with regards to binding paths, but you have used lower cased property names in your XAML. (You can find out more from the 'Case and Whitespace in XAML' section of the XAML Overview (WPF) page at MSDN.
XAML is generally speaking case sensitive. For purposes of resolving backing types, WPF XAML is case sensitive by the same rules that the CLR is case sensitive. Object elements, property elements, and attribute names must all be specified by using the sensitive casing when compared by name to the underlying type in the assembly, or to a member of a type.
2.
You do not need to set the Password property of the PasswordBox in your OnPasswordPropertyChanged handler, although this shouldn't cause your described problem.

Databinding custom objects

public class Employee : INotifyPropertyChanged
{
// Private Properties
private string _name;
private List<string> _address;
// The Public properties for which the getters and setters are implemented appropriately (raising OnPropertyChanged event)
}
public class EmployeeRecords: ObservableCollection<Employee>
{
public bool AddEmployee(Employee employee)
{
Add(employee);
return true;
}
public bool RemoveEmployee(int index)
{
if (Count > 0)
{
RemoveAt(index); // is the same as doing 'RemoveAt(SelectedIndex);'
}
return true;
}
}
**XAML:**
<Window x:Class="EmployeeInfo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:src="clr-namespace:EmployeeInfo"
Name="Page1" Height="225" Width="610"
Title="DATABINDING DEMO">
<Window.Resources>
<DataTemplate x:Key="EmployeeTemplate">
<StackPanel>
<TextBlock Text="{Binding Path=Name}" />
<TextBlock Text="{Binding Path=EmpId}"/>
<TextBlock Text="{Binding Path=Designation}"/>
</StackPanel>
</DataTemplate>
<src:EmployeeRecords x:Key="EmpInfo"/>
</Window.Resources>
<Window.DataContext>
<Binding Source="{StaticResource EmpInfo}"/>
</Window.DataContext>
<Canvas Height="190" Width="600">
<Label Name="lblName" Height="30" Width="50" Canvas.Top="0" Canvas.Left="0" >Name</Label>
<TextBox Name="txtBoxName" Height="30" Width="125" Text="{Binding Path=Name}" Canvas.Top="5" Canvas.Left="60" />
<Label Name="lblEmpId" Height="30" Width="50" Canvas.Top="40" Canvas.Left="0" >EmpId</Label>
<TextBox Name="txtBoxEmpId" Height="30" Width="50" Text="{Binding Path=EmpId}" Canvas.Top="40" Canvas.Left="60" />
<Label Name="lblDesignation" Height="30" Width="50" Canvas.Top="75" Canvas.Left="0" >Designation</Label>
<TextBox Name="txtBoxDesignation" Height="30" Width="50" Text="{Binding Path=Designation}" Canvas.Top="75" Canvas.Left="60" />
<Label Name="lblAddress" Height="30" Width="50" Canvas.Top="115" Canvas.Left="0" >Address</Label>
<TextBox Name="txtBoxAddress" Height="30" Width="50" Text="{Binding Path=Address}" Canvas.Top="115" Canvas.Left="60" />
<TextBox Name="txtBoxAddress2" Height="30" Width="50" Text="{Binding Path=Address}" Canvas.Top="115" Canvas.Left="120" />
<Button Height="30" Width="50" Canvas.Top="155" Canvas.Left="0" Content="Update" Click="UpdateButton_Click"/>
<Button Height="30" Width="50" Canvas.Top="155" Canvas.Left="60" Content="Submit" Click="SubmitButton_Click"/>
<Button Height="30" Width="50" Canvas.Top="155" Canvas.Left="120" Content="Remove" Click="RemoveButton_Click" />
<ListBox SelectedIndex="{Binding SelectedIndex}"
MouseDoubleClick="LstEmployee_MouseDoubleClick" Name="lstEmployee" Height="180" Width="190"
Canvas.Top="5" Canvas.Left="200" ItemsSource="{Binding}" ItemTemplate="{StaticResource EmployeeTemplate}"/>
<ListBox Name="listAddress" Height="180" Width="190" Canvas.Top="5" Canvas.Left="400" ItemsSource="{Binding Path=/Address}"/>
</Canvas>
</Window>
MainWindow.xaml.cs:
public partial class MainWindow : Window
{
private EmployeeRecords _empRecords;
public MainWindow()
{
InitializeComponent();
Initialize();
lstEmployee.ItemsSource = _empRecords;
}
.
.
.
.
}
I'm trying to display all the properties of Employee in the 1st listBox and just the addresses in the 2nd ListBox. Can someone tell me what i'm doing wrong here?
Since I can't explicitly access the Employee object within EmployeeRecords, how can I bind the Address list inside of Employee to a control?
Thanks in advance!
Shanks
Assuming that you want to display the address of the selected Employee in the second ListBox, the following should work.
<ListBox Grid.Row="1" Name="listAddress" Height="180" Width="190" Canvas.Top="5" Canvas.Left="400" ItemsSource="{Binding ElementName=lstEmployee, Path=SelectedItem.Address}"/>
Note:
I have assumed that the public property name for the backing field private List<string> _address; is Address

Binding a textbox from a secondary window is not updating the property

I need to bind the text property of a textbox that it is located in a secondary window to a property that is defined in the corresponding view model of that secondary window
XAML CODE:
<Window x:Class="RG.IOManager.Views.PreferencesDialog"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:genericClasses="clr-namespace:RG.IOManager.GenericClasses"
xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
Title="Setup" Height="131" Width="332"
WindowStartupLocation="CenterOwner"
ShowInTaskbar="False"
WindowStyle="ToolWindow"
>
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="../ResourceDictionary.xaml" />
<ResourceDictionary Source="../ScrollBarTemplate.xaml" />
<ResourceDictionary Source="../Styles.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="10*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Label Content="Cycle Time" Grid.Row="0" Grid.Column="0" Height="28" HorizontalAlignment="Left" Margin="10,10,0,20" Name="label1" VerticalAlignment="Top" />
<StackPanel Grid.Row="0" Grid.Column="1" Width="190" Orientation="Horizontal">
<!--
<xctk:IntegerUpDown Name="TbMainCycleTime" Margin="10,10,0,20" Width="50" Height="25" HorizontalContentAlignment="Right"
Increment="1" Maximum="5000" Minimum="0" ShowButtonSpinner="False"/>
-->
<TextBox Name="TbMainCycleTime" Margin="10,10,0,20" Width="50" Height="25" HorizontalContentAlignment="Right" Validation.ErrorTemplate="{StaticResource ErrorTemplate}" Style="{StaticResource textBoxErrorTooltip}" >
<TextBox.Text>
<Binding Source="PreferencesDialog" Path="CycleTime" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged" >
<Binding.ValidationRules>
<genericClasses:IntegersValidation Min="0" Max="1000" />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
<!--<TextBox Name="TbMainCycleTime" Margin="10,10,0,20" Width="50" Height="25" HorizontalContentAlignment="Right" />-->
<Label Content="ms" Margin="1,10,10,20"/>
</StackPanel>
<StackPanel Grid.Row="1" Grid.Column="1" Width="190" Orientation="Horizontal">
<Button Content="Update" Height="23" HorizontalAlignment="Left" Margin="5,0,10,0" Name="btUpdate" VerticalAlignment="Top" Width="75" Click="btUpdate_Click" />
<Button Content="Cancel" Height="23" HorizontalAlignment="Left" Margin="5,0,10,0" Name="btCancel" VerticalAlignment="Top" Width="75" Click="btCancel_Click" />
</StackPanel>
</Grid>
CS CODE:
/// <summary>
/// Interaction logic for PreferencesDialogue.xaml
/// </summary>
public partial class PreferencesDialog : Window, INotifyPropertyChanged
{
#region Binding Properties
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Main cycle time
/// </summary>
public int CycleTime
{
get { return _CycleTime; }
set
{
_CycleTime = value;
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs("CycleTime"));
}
}
}
private int _CycleTime;
#endregion
private IOManager _receiver;
public PreferencesDialog(IOManager receiver)
{
this._receiver = receiver;
InitializeComponent();
//this.TbMainCycleTime.Text = _receiver.globalBindingProperties.MainCycleTime.ToString();
this.CycleTime = _receiver.globalBindingProperties.MainCycleTime;
}
private void btUpdate_Click(object sender, RoutedEventArgs e)
{
_receiver.globalBindingProperties.MainCycleTime = Convert.ToInt32(this.TbMainCycleTime.Text);
this.Close();
}
private void btCancel_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
}
Can someone help me to find what i did wrong? Thanks in advance
your approach is wrong. however if you change these two thing your problem will be solved:
first set DataContext of the Window:
public PreferencesDialog(IOManager receiver)
{
this.DataContext = this;
this._receiver = receiver;
InitializeComponent();
//this.TbMainCycleTime.Text = _receiver.globalBindingProperties.MainCycleTime.ToString();
this.CycleTime = _receiver.globalBindingProperties.MainCycleTime;
}
second remove 'Source' from TextBox.Text.Binding since the source is the dataContext.
<TextBox Name="TbMainCycleTime" Margin="10,10,0,20" Width="50" Height="25" HorizontalContentAlignment="Right" Validation.ErrorTemplate="{StaticResource ErrorTemplate}" Style="{StaticResource textBoxErrorTooltip}" >
<TextBox.Text>
<Binding Path="CycleTime" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged" >
<Binding.ValidationRules>
<genericClasses:IntegersValidation Min="0" Max="1000" />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
Have you assigned your viewmodel as datacontext to window? (class in which you have defined CycleTime)
Secondly, are you going to change cycle time for UI. You are using two way binding between TextBox and CycleTime property.
Check if this link, where I've created type safe text box extnsions. Though, article is about silverlight, you can easily use in WPF.
Change your xaml as
<Window x:Class="RG.IOManager.Views.PreferencesDialog" x:Name="PreferencesDialog"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

Resources