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
Related
My problem is, after the SelectionChanged event nothing happen. The TextBox didnt get any new value relaited to the ComboBox. When I reload the ViewModel (Go page 1 and back), the TexBox has his new value relaited to the ComboBox.
Below you can see what I have on till now.
View:
<StackPanel Orientation="Vertical" Grid.Row="1">
<Border Width="150" Height="150" CornerRadius="80" BorderThickness="1" BorderBrush="Gray" HorizontalAlignment="Center">
<Border.Background>
<ImageBrush ImageSource="/Assets/FEBSolution.png"/>
</Border.Background>
</Border>
<TextBlock x:Name="EmployerName" Text="{Binding EmployerName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Center" Margin="0 10 0 0" FontWeight="Bold"/>
<TextBlock x:Name="EmpDescription" Text="{Binding EmpDescription, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" FontSize="11" HorizontalAlignment="Center" Opacity="0.8"/>
<TextBlock x:Name="EmpMotto" Text="{Binding EmpMotto, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" FontSize="8" HorizontalAlignment="Center" Opacity="0.8"/>
<StackPanel Margin="20">
<StackPanel Orientation="Horizontal" Margin="0 3" HorizontalAlignment="Left">
<materialDesign:PackIcon Kind="Location" />
<TextBlock x:Name="EmpLocation" Text="{Binding EmpLocation, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Margin="10 0"/>
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="0 3" HorizontalAlignment="Left">
<materialDesign:PackIcon Kind="Phone" />
<TextBlock x:Name="EmpPhone" Text="{Binding EmpPhone, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Margin="10 0"/>
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="0 3" HorizontalAlignment="Left">
<materialDesign:PackIcon Kind="Email" />
<TextBlock x:Name="EmpEmail" Text="{Binding EmpEmail, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Margin="10 0"/>
</StackPanel>
</StackPanel>
</StackPanel>
<ComboBox x:Name="cmbEmployer" Grid.Row="2" SelectedValuePath="ID" SelectedValue="{Binding ID}" ItemsSource="{Binding contractDetails}" SelectedItem="{Binding ContractSelectedItem, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" DisplayMemberPath="EmployerName" materialDesign:HintAssist.Hint="Employer" Width="200" HorizontalAlignment="Center" Margin="10">
<ie:Interaction.Triggers>
<ie:EventTrigger EventName="SelectionChanged">
<ie:InvokeCommandAction Command="{Binding SelectionChangedCommand, UpdateSourceTrigger=PropertyChanged}" CommandParameter="{Binding ElementName=cmbEmployer, Path=SelectedItem}"/>
</ie:EventTrigger>
</ie:Interaction.Triggers>
</ComboBox>
ViewModel:
private ContractDetail _contractSelectedItem;
public ContractDetail ContractSelectedItem
{
get { return _contractSelectedItem; }
set
{
_contractSelectedItem = value;
EmployerName = _contractSelectedItem.EmployerName;
EmpDescription = _contractSelectedItem.EmpDescription;
EmpMotto = _contractSelectedItem.EmpMotto;
EmpLocation = _contractSelectedItem.EmpLocation;
EmpPhone = _contractSelectedItem.EmpPhone;
EmpEmail = _contractSelectedItem.EmpEmail;
OnPropertyChanged(nameof(ContractSelectedItem));
}
}
public List<ContractDetail> contractDetails { get; set; }
#region Public all Commands
//Command for change User
public ICommand ChangeUserCommand { get; private set; }
public ICommand CloseWindowCommand { get; private set; }
public ICommand SelectionChangedCommand { get; private set; }
#endregion
//PRWContext for general use
private PRWContext context = new PRWContext();
public ApplicationSettingViewModel()
{
// Load the data from PRW Database
LoadUserData();
BindContractComboBox();
//Commands
ChangeUserCommand = new RelayCommand(() => ExecuteChangeUserCommand());
CloseWindowCommand = new RelayCommand(() => ExecuteCloseWindowCommand());
SelectionChangedCommand = new RelayCommand(() => ExecuteSelectionChangedCommand());
}
private void ExecuteCloseWindowCommand()
{
foreach (Window window in Application.Current.Windows)
{
if (window is ApplicationSettingWindow)
{
window.Close();
break;
}
}
}
private void ExecuteChangeUserCommand()
{
UserSettingWindow view = new UserSettingWindow();
view.Show();
foreach (Window window in Application.Current.Windows)
{
if (window is ApplicationSettingWindow)
{
window.Close();
break;
}
}
}
private void ExecuteSelectionChangedCommand()
{
var item = context.ContractDetails.ToList();
contractDetails = item;
}
//Load the user data
private void LoadUserData()
{
UserName = Settings.Default["UserName"].ToString();
JobDescription = Settings.Default["UsrJobDescription"].ToString();
Motto = Settings.Default["UsrMotto"].ToString();
Street = Settings.Default["UsrStreet"].ToString();
City = Settings.Default["UsrCity"].ToString();
Country = Settings.Default["UsrCountry"].ToString();
PhoneNumber = Settings.Default["UsrPhoneNumber"].ToString();
Email = Settings.Default["UsrEmail"].ToString();
}
private void BindContractComboBox()
{
var item = context.ContractDetails.ToList();
contractDetails = item;
}
#region PropertyChanged EventHandler
//propertychanged eventhandler
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
For sure there is somthing missing, otherwise it will do the magic ;) I just dont know where i miss something. Any help will be welcome.
You aren't calling the OnPropertyChanged() for
EmployerName,
EmpDescription,
EmpMotto,
EmpLocation,
EmpPhone,
EmpEmail
that's why your view doesn't get updated, and why are you actually using these separate properties when you can just use the ContractSelectedItem directly. You can access the nested properties like this "ContractSelectedItem.EmployerName"
Try this in your viewmodel
private ContractDetail _contractSelectedItem;
public ContractDetail ContractSelectedItem
{
get { return _contractSelectedItem; }
set
{
_contractSelectedItem = value;
OnPropertyChanged(nameof(ContractSelectedItem));
}
}
and change your view's binding like this
<StackPanel Orientation="Vertical" Grid.Row="1">
<Border Width="150" Height="150" CornerRadius="80" BorderThickness="1" BorderBrush="Gray" HorizontalAlignment="Center">
<Border.Background>
<ImageBrush ImageSource="/Assets/FEBSolution.png"/>
</Border.Background>
</Border>
<TextBlock x:Name="EmployerName" Text="{Binding ContractSelectedItem.EmployerName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Center" Margin="0 10 0 0" FontWeight="Bold"/>
<TextBlock x:Name="EmpDescription" Text="{Binding ContractSelectedItem.EmpDescription, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" FontSize="11" HorizontalAlignment="Center" Opacity="0.8"/>
<TextBlock x:Name="EmpMotto" Text="{Binding ContractSelectedItem.EmpMotto, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" FontSize="8" HorizontalAlignment="Center" Opacity="0.8"/>
<StackPanel Margin="20">
<StackPanel Orientation="Horizontal" Margin="0 3" HorizontalAlignment="Left">
<materialDesign:PackIcon Kind="Location" />
<TextBlock x:Name="EmpLocation" Text="{Binding ContractSelectedItem.EmpLocation, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Margin="10 0"/>
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="0 3" HorizontalAlignment="Left">
<materialDesign:PackIcon Kind="Phone" />
<TextBlock x:Name="EmpPhone" Text="{Binding ContractSelectedItem.EmpPhone, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Margin="10 0"/>
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="0 3" HorizontalAlignment="Left">
<materialDesign:PackIcon Kind="Email" />
<TextBlock x:Name="EmpEmail" Text="{Binding ContractSelectedItem.EmpEmail, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Margin="10 0"/>
</StackPanel>
</StackPanel>
</StackPanel>
<ComboBox x:Name="cmbEmployer" Grid.Row="2" SelectedValuePath="ID" SelectedValue="{Binding ID}" ItemsSource="{Binding contractDetails}" SelectedItem="{Binding ContractSelectedItem, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" DisplayMemberPath="EmployerName" materialDesign:HintAssist.Hint="Employer" Width="200" HorizontalAlignment="Center" Margin="10">
<ie:Interaction.Triggers>
<ie:EventTrigger EventName="SelectionChanged">
<ie:InvokeCommandAction Command="{Binding SelectionChangedCommand, UpdateSourceTrigger=PropertyChanged}" CommandParameter="{Binding ElementName=cmbEmployer, Path=SelectedItem}"/>
</ie:EventTrigger>
</ie:Interaction.Triggers>
</ComboBox>
Also, there doesn't seem a reason to use the SelectionChanged event when you are just repopulating the contractDetails property every time the selection changes. Try to remove it if you aren't doing anything other then just repopulating the property.
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.
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.
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
I am making a Silverlight 4.0 Navigation Application with Authentication Service to manage users, log in/out and so forth.
I have used the msdn tutorial on this page: http://msdn.microsoft.com/en-us/library/ee942451%28v=vs.91%29.aspx
It works great. I can create users with some custom profile properties and log in and out.
The problem is my create user form. As in the tutorial I have in my service project made a class called NewUser, with data annotations. These seems to work, as if I try to create a user with a invalid field, the creation fails, and i get an exception, with the message that there are validation errors.
I would like this validation to work with my form. In other forms I just bind an instance of a class to the form and set the binding for each field with validationOnException to true and notifyOnValidationError to true.
I have made the bindings in the create user form as in my other forms, but they do not seem to work. I have tried to set a breakpoint in a set of a property on the NewUser class. It looks like it do not get called/used at all.
This is most likely a simple matter of me missing something, but I can not found out what. Does it have anything to do with the fact that the NewUser class is in my service project and the form is in the client project. I hope you guys can help me.
My code for the NewUser class
public class NewUser
{
private string username;
[Key]
[Required()]
public string UserName { get; set; }
[Key]
[Required()]
[RegularExpression(#"^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$", ErrorMessage="Invalid email. An email must use the format username#mycompany.com")]
public string Email { get; set; }
[Required()]
public string Firstname { get; set; }
[Required()]
public string Lastname { get; set; }
[Required()]
public DateTime Birthsday { get; set; }
[Required()]
public bool SentNewsletter { get; set; }
[Required()]
public bool SentReminders { get; set; }
[Required()]
public string Password { get; set; }
[CustomValidation(typeof(RegistrationValidator), "IsPasswordConfirmed")]
public string ConfirmPassword { get; set; }
[Required()]
public string SecurityQuestion { get; set; }
[Required()]
public string SecurityAnswer { get; set; }
}
My create user form xaml
<navigation:Page x:Class="OenskePortalen.Views.Pages.CreateNewUser"
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"
mc:Ignorable="d"
xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
xmlns:input="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data.Input"
xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
xmlns:uc="clr-namespace:OenskePortalen.Views.Controls"
d:DesignWidth="640" d:DesignHeight="680"
Title="CreateNewUser Page">
<Grid x:Name="LayoutRoot" Background="White">
<Grid.RowDefinitions>
<RowDefinition Height="50" />
<RowDefinition Height="40"/>
<RowDefinition Height="40"/>
<RowDefinition Height="40"/>
<RowDefinition Height="40"/>
<RowDefinition Height="40"/>
<RowDefinition Height="40"/>
<RowDefinition Height="40"/>
<RowDefinition Height="40"/>
<RowDefinition Height="40"/>
<RowDefinition Height="40"/>
<RowDefinition Height="40"/>
<RowDefinition Height="40"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="180"/>
<ColumnDefinition Width="10"/>
<ColumnDefinition Width="160"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<uc:InfoBox Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="4" DisplayText="Her kan du oprette dig som bruger på ØnskePortalen" VerticalAlignment="Top"/>
<TextBlock Grid.Row="1" Grid.Column="0" Text="Brugernavn" VerticalAlignment="Center"/>
<TextBlock Grid.Row="1" Grid.Column="1" Text=":" VerticalAlignment="Center"/>
<TextBox Grid.Row="1" Grid.Column="2" x:Name="txtUsername" Text="{Binding UserName, Mode=TwoWay, ValidatesOnExceptions=True, NotifyOnValidationError=True}" VerticalAlignment="Center" Width="150" Margin="5" HorizontalAlignment="Left" />
<TextBlock Grid.Row="2" Grid.Column="0" Text="Fornavn" VerticalAlignment="Center"/>
<TextBlock Grid.Row="2" Grid.Column="1" Text=":" VerticalAlignment="Center"/>
<TextBox Grid.Row="2" Grid.Column="2" x:Name="txtFirstname" Text="{Binding Firstname, Mode=TwoWay, ValidatesOnExceptions=True, NotifyOnValidationError=True}" VerticalAlignment="Center" Width="150" Margin="5" HorizontalAlignment="Left" />
<TextBlock Grid.Row="3" Grid.Column="0" Text="Efternavn" VerticalAlignment="Center"/>
<TextBlock Grid.Row="3" Grid.Column="1" Text=":" VerticalAlignment="Center"/>
<TextBox Grid.Row="3" Grid.Column="2" x:Name="txtLastname" Text="{Binding Lastname, Mode=TwoWay, ValidatesOnExceptions=True, NotifyOnValidationError=True}" VerticalAlignment="Center" Width="150" Margin="5" HorizontalAlignment="Left" />
<TextBlock Grid.Row="4" Grid.Column="0" Text="Email" VerticalAlignment="Center"/>
<TextBlock Grid.Row="4" Grid.Column="1" Text=":" VerticalAlignment="Center"/>
<TextBox Grid.Row="4" Grid.Column="2" x:Name="txtEmail" Text="{Binding Email, Mode=TwoWay, ValidatesOnExceptions=True, NotifyOnValidationError=True}" VerticalAlignment="Center" Width="150" Margin="5" HorizontalAlignment="Left" />
<TextBlock Grid.Row="5" Grid.Column="0" Text="Adgangskode" VerticalAlignment="Center"/>
<TextBlock Grid.Row="5" Grid.Column="1" Text=":" VerticalAlignment="Center"/>
<PasswordBox Grid.Row="5" Grid.Column="2" x:Name="txtPassword" Password="{Binding Password, Mode=TwoWay, ValidatesOnExceptions=True, NotifyOnValidationError=True}" VerticalAlignment="Center" Width="150" Margin="5" />
<TextBlock Grid.Row="6" Grid.Column="0" Text="Gentag adgangskode" VerticalAlignment="Center"/>
<TextBlock Grid.Row="6" Grid.Column="1" Text=":" VerticalAlignment="Center"/>
<PasswordBox Grid.Row="6" Grid.Column="2" x:Name="txtPasswordRepeat" Password="{Binding PasswordConfirm, Mode=TwoWay, ValidatesOnExceptions=True, NotifyOnValidationError=True}" VerticalAlignment="Center" Width="150" Margin="5" />
<TextBlock Grid.Row="7" Grid.Column="0" Text="Sikkerhedsspørgsmål" VerticalAlignment="Center"/>
<TextBlock Grid.Row="7" Grid.Column="1" Text=":" VerticalAlignment="Center"/>
<TextBox Grid.Row="7" Grid.Column="2" x:Name="txtPasswordQuestion" Text="{Binding SecurityQuestion, Mode=TwoWay, ValidatesOnExceptions=True, NotifyOnValidationError=True}" VerticalAlignment="Center" Width="150" Margin="5" HorizontalAlignment="Left" />
<TextBlock Grid.Row="8" Grid.Column="0" Text="Sikkerhedssvar" VerticalAlignment="Center"/>
<TextBlock Grid.Row="8" Grid.Column="1" Text=":" VerticalAlignment="Center"/>
<TextBox Grid.Row="8" Grid.Column="2" x:Name="txtPasswordAnswer" Text="{Binding SecurityAnswer, Mode=TwoWay, ValidatesOnExceptions=True, NotifyOnValidationError=True}" VerticalAlignment="Center" Width="150" Margin="5" HorizontalAlignment="Left" />
<TextBlock Grid.Row="9" Grid.Column="0" Text="Fødselsdag" VerticalAlignment="Center"/>
<TextBlock Grid.Row="9" Grid.Column="1" Text=":" VerticalAlignment="Center"/>
<sdk:DatePicker Grid.Row="9" Grid.Column="2" x:Name="dpBirthsday" SelectedDate="{Binding Birthsday, Mode=TwoWay, ValidatesOnExceptions=True, NotifyOnValidationError=True}" VerticalAlignment="Center" Width="150" Margin="5" HorizontalAlignment="Left"/>
<TextBlock Grid.Row="10" Grid.Column="0" Text="Nyhedsbrev" VerticalAlignment="Center"/>
<TextBlock Grid.Row="10" Grid.Column="1" Text=":" VerticalAlignment="Center"/>
<CheckBox Grid.Row="10" Grid.Column="2" x:Name="cboxNewsletter" IsChecked="{Binding SentNewsletter, Mode=TwoWay, ValidatesOnExceptions=True, NotifyOnValidationError=True}" VerticalAlignment="Center" Margin="5"/>
<TextBlock Grid.Row="11" Grid.Column="0" Text="Påmindelser om fødselsdage" VerticalAlignment="Center"/>
<TextBlock Grid.Row="11" Grid.Column="1" Text=":" VerticalAlignment="Center" />
<CheckBox Grid.Row="11" Grid.Column="2" x:Name="cboxReminders" IsChecked="{Binding SentReminders, Mode=TwoWay, ValidatesOnExceptions=True, NotifyOnValidationError=True}" VerticalAlignment="Center" Margin="5"/>
<StackPanel Grid.Row="12" Grid.Column="0" Grid.ColumnSpan="3" HorizontalAlignment="Right" Orientation="Horizontal" >
<Button x:Name="btnCreate" Style="{StaticResource GreenButton}" Background="{StaticResource GreenGradientBrush}" Height="20" Margin="5" Click="btnCreate_Click" Cursor="Hand" >
<TextBlock Text="Opret ny bruger" Style="{StaticResource textStyleBlack}" />
</Button>
<Button x:Name="btnCancel" Style="{StaticResource BlueButton}" Background="{StaticResource BlueGradientBrush}" Height="20" Margin="5" Click="btnCancel_Click" Cursor="Hand" >
<TextBlock Text="Annuller" Style="{StaticResource textStyleBlack}" />
</Button>
</StackPanel>
<input:ValidationSummary Grid.Row="13" Grid.Column="0" Grid.ColumnSpan="3" />
</Grid>
And my create user form code behind
public partial class CreateNewUser : Page
{
private NewUser user;
public CreateNewUser()
{
InitializeComponent();
user = new NewUser();
LayoutRoot.DataContext = user;
dpBirthsday.SelectedDate = DateTime.Now;
cboxNewsletter.IsChecked = true;
cboxReminders.IsChecked = true;
}
private void btnCreate_Click(object sender, RoutedEventArgs e)
{
updateValidation();
if (!Validation.GetHasError(LayoutRoot))
{
RegistrationDomainContext context = new RegistrationDomainContext();
NewUser user = new NewUser();
try
{
user.UserName = txtUsername.Text;
user.Password = txtPassword.Password;
user.Email = txtEmail.Text;
user.ConfirmPassword = txtPassword.Password;
user.SecurityQuestion = txtPasswordQuestion.Text;
user.SecurityAnswer = txtPasswordAnswer.Text;
user.Firstname = txtFirstname.Text;
user.Lastname = txtLastname.Text;
user.Birthsday = dpBirthsday.SelectedDate.GetValueOrDefault(DateTime.Now);
user.SentNewsletter = cboxNewsletter.IsChecked.GetValueOrDefault(true);
user.SentReminders = cboxReminders.IsChecked.GetValueOrDefault(true);
context.NewUsers.Add(user);
context.SubmitChanges(RegisterUser_Completed, null);
}
catch (Exception exc)
{
ErrorWindow w = new ErrorWindow(exc);
w.Show();
}
} // end validation
}
private void RegisterUser_Completed(SubmitOperation so)
{
if (so.HasError)
{
ErrorWindow ew = new ErrorWindow(so.Error);
ew.Show();
so.MarkErrorAsHandled();
}
else
{
LoginParameters lp = new LoginParameters(txtUsername.Text, txtPassword.Password);
}
}
private void btnCancel_Click(object sender, RoutedEventArgs e)
{
MainPage mp = Application.Current.RootVisual as MainPage;
mp.contentFrame.Navigate(new Uri("/home", UriKind.Relative));
}
private void updateValidation()
{
foreach (var current in LayoutRoot.Children)
{
if (current is TextBox)
(current as TextBox).GetBindingExpression(TextBox.TextProperty).UpdateSource();
if (current is PasswordBox)
(current as PasswordBox).GetBindingExpression(PasswordBox.PasswordProperty).UpdateSource();
}
}
}
I believe that you can't databind to a private field - try changing user in your code-behind to a public property (and maybe look at implementing INotifyPropertyChanged).