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.
Related
Unable to call a grid inside a listbox anymore... my xaml is as follows.
<UserControl x:Class="WPFPurpleButtonTest.InstrumentUserControl"
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:local="clr-namespace:WPFPurpleButtonTest"
mc:Ignorable="d"
d:DesignHeight="750" d:DesignWidth="900">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<TabControl x:Name="tabControl" HorizontalAlignment="Left" Height="706" Margin="24,34,0,-212" VerticalAlignment="Top" Width="850" Grid.RowSpan="2">
<TabItem Header="TabItem" Name="mainTab">
<Grid Background="#FFE5E5E5" Margin="0,0,-396,-255">
<Label x:Name="colourName" Content="PURPLE" HorizontalAlignment="Left" Height="93" Margin="284,88,0,0" VerticalAlignment="Top" Width="243" FontWeight="Bold" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" FontSize="50" Foreground="#FFDC00FF"/>
<Button x:Name="testButton" Content="Button" HorizontalAlignment="Left" Margin="365,181,0,0" VerticalAlignment="Top" Width="75" Click="TestButton_Click"/>
<Label x:Name="label" Content="Row Size" HorizontalAlignment="Left" Margin="198,211,0,0" VerticalAlignment="Top" Foreground="#FFDC00FF"/>
<Label x:Name="label_Copy" Content="Column Size" HorizontalAlignment="Left" Margin="432,211,0,0" VerticalAlignment="Top" Foreground="#FFDC00FF"/>
<Button x:Name="createGrid" Content="Create Grid" HorizontalAlignment="Left" Margin="365,273,0,0" VerticalAlignment="Top" Width="75" Click="CreateGrid_Click"/>
<TextBox x:Name="rowSizeText" HorizontalAlignment="Left" Height="23" Margin="278,214,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="62"/>
<TextBox x:Name="columnSizeText" HorizontalAlignment="Left" Height="23" Margin="522,215,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="62"/>
</Grid>
</TabItem>
<TabItem Header="TabItem" Name="gridTab">
<ListBox x:Name="listbox1" ScrollViewer.VerticalScrollBarVisibility="Disabled">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel IsItemsHost="True" Orientation="Vertical" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Margin="20" HorizontalAlignment="Center">
<Viewbox>
<Grid x:Name="wellGrid" Grid.Row="1" ShowGridLines="True"
local:GridHelpers.RowCount="{Binding RowCount}"
local:GridHelpers.ColumnCount="{Binding ColumnCount}" Margin="15,15,15,15" />
</Viewbox>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</TabItem>
</TabControl>
</Grid>
</UserControl>
I want to be able to call wellGrid.Children like I used to when the grid was not in a listbox but not entirely sure how to do that now the grid is in the listbox.
The Grid is part of theDataTemplatethat is assigned to theListBoxItem. You need to get theContentPresenterof the item. This is where theDataTemplate` is applied.
private void Button_Click(object sender, RoutedEventArgs e)
{
int selectedItemIndex = this.listbox1.SelectedIndex;
if (selectedItemIndex == -1)
{
return;
}
var itemContainer = this.listbox1.ItemContainerGenerator.ContainerFromIndex(selectedItemIndex) as ListBoxItem;
if (TryFindChildElement(itemContainer, out ContentPresenter contentPresenter))
{
// Get the Grid
var grid = contentPresenter.ContentTemplate.FindName("wellGrid", myContentPresenter) as Grid;
}
}
// Helper to traverse the visual tree
private bool TryFindChildElement<TElement>(DependencyObject parent, out TElement resultElement) where TElement : DependencyObject
{
resultElement = null;
for (var childIndex = 0; childIndex < VisualTreeHelper.GetChildrenCount(parent); childIndex++)
{
DependencyObject childElement = VisualTreeHelper.GetChild(parent, childIndex);
if (childElement is Popup popup)
{
childElement = popup.Child;
}
if (childElement is TElement)
{
resultElement = childElement as TElement;
return true;
}
if (TryFindChildElement(childElement, out resultElement))
{
return true;
}
}
return false;
}
Im using several controls in my main window.
one grid at top that has a list of licenses and i want to display the information of the license each time i change the selection of the grid
MainWindow:
<dx:DXWindow
x:Class="LicenceManagerWPF.Forms.frmCustomerLicense"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:dx="http://schemas.devexpress.com/winfx/2008/xaml/core"
dx:ThemeManager.ThemeName="Office2016"
xmlns:ctr="clr-namespace:LicenceManagerWPF.Controls"
Title="CustomerLicence" Height="800" Width="1000"
WindowStartupLocation="CenterScreen" Loaded="DXWindow_Loaded">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="50"/>
<RowDefinition MinHeight="200" Height="200*"/>
<RowDefinition Height="200*"/>
<RowDefinition MinHeight="25" Height="25"/>
</Grid.RowDefinitions>
<StackPanel x:Name="Stack_Top" Orientation="Horizontal" Grid.Row="0" >
<dx:SimpleButton x:Name="btnRefresh" Style="{StaticResource ResourceKey=BtnSmall}" ToolTip="Refresh Licenses" Glyph="{dx:DXImage Image=Refresh_32x32.png}" Content="Resfresh" />
<dx:SimpleButton x:Name="btndNew" Style="{StaticResource ResourceKey=BtnSmall}" ToolTip="New License" Glyph="{dx:DXImage Image=New_32x32.png}" Content="New Customer" />
<dx:SimpleButton x:Name="btnDelete" Style="{StaticResource ResourceKey=BtnSmall}" ToolTip="Delete Licence" Content="Delete" Glyph="{dx:DXImage Image=Cancel_32x32.png}"/>
<dx:SimpleButton x:Name="btnEdit" Style="{StaticResource ResourceKey=BtnSmall}" ToolTip="Edit Customer" Glyph="{dx:DXImage Image=EditContact_32x32.png}" />
<TextBlock Text="Customer: " FontSize="20" Margin="5"/>
<TextBlock Text="{Binding Customer.Name}" Margin="5" FontSize="20"/>
</StackPanel>
<ctr:Licences x:Name="grdLicenses" Grid.Row="1">
</ctr:Licences>
<Grid Grid.Row="2">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition />
</Grid.ColumnDefinitions>
<ctr:LicenseDetail x:Name="ct_LicenseDetail" Grid.Column="0"/>
<ctr:LicenceLog x:Name="ct_LicenseLog" Grid.Column="1"/>
</Grid>
</Grid>
The grid is ctr_Licenses and the other control is LicenseDetail which should show the information of the license selected, this is the licenseDetail control:
<UserControl
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:dxg="http://schemas.devexpress.com/winfx/2008/xaml/grid"
xmlns:dxe="http://schemas.devexpress.com/winfx/2008/xaml/editors"
xmlns:dx="http://schemas.devexpress.com/winfx/2008/xaml/core" x:Class="LicenceManagerWPF.Controls.LicenseDetail"
mc:Ignorable="d"
d:DesignHeight="500" d:DesignWidth="600" x:Name="ctrl_LicenseDetail" >
<UserControl.Resources>
<Style x:Key="SmallMargin" TargetType="FrameworkElement">
<Setter Property="Margin" Value="5"/>
</Style>
<Style x:Key="TabMargin" TargetType="FrameworkElement" >
<Setter Property="Margin" Value="2.5"/>
</Style>
<Style x:Key="SmalllMarginTextBlock" BasedOn="{StaticResource SmallMargin}" TargetType="{x:Type TextBlock}">
</Style>
<Style x:Key="SmallMarginDropDown" BasedOn="{StaticResource SmallMargin }" TargetType="dx:DropDownButton" >
</Style>
<Style x:Key="SmallMarginText" BasedOn="{StaticResource SmallMargin}" TargetType="TextBox">
</Style>
<Style x:Key="ckkStyle" TargetType="dxe:CheckEdit" BasedOn="{StaticResource TabMargin}">
<Setter Property="IsReadOnly" Value="True"/>
</Style>
</UserControl.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="40" />
<RowDefinition Height="30" />
<RowDefinition Height="30" />
<RowDefinition Height="30"/>
<RowDefinition Height="100*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<TextBlock Text="License Detail" FontSize="16" Grid.ColumnSpan="2" VerticalAlignment="Center" Margin="10" Grid.Row="0" />
<TextBlock Text="Serial Number:" Grid.Column="0" Grid.Row="1" Style="{StaticResource ResourceKey=SmalllMarginTextBlock}"/>
<TextBlock Text="{Binding Path=DataContext.SelectedLicense.SerialNumber, UpdateSourceTrigger=PropertyChanged, RelativeSource={RelativeSource AncestorType=Window}}" x:Name="txtSerialNum" Grid.Column="1" Grid.Row="1" Style="{StaticResource ResourceKey=SmalllMarginTextBlock}"/>
<TextBlock Text="Product:" Grid.Column="0" Grid.Row="2" Style="{StaticResource ResourceKey=SmalllMarginTextBlock}" />
<StackPanel Orientation="Horizontal" Grid.Row="2" Grid.Column="1">
<dx:DropDownButton x:Name="dropDownButton" Width="180" Content="Product" Style="{StaticResource SmallMarginDropDown}">
</dx:DropDownButton>
<TextBlock Text="Status:" Style="{StaticResource SmalllMarginTextBlock}" />
<TextBlock Text="" Width="150" Style="{StaticResource SmalllMarginTextBlock}" />
</StackPanel>
<TextBlock Text="Description:" Style="{StaticResource SmalllMarginTextBlock}" Grid.Row="3" Grid.Column="0" />
<TextBox Text="" HorizontalAlignment="Left" Grid.Column="1" Grid.Row="3" Style="{StaticResource SmallMargin}" Width="350" />
<dx:DXTabControl Grid.Row="4" Grid.ColumnSpan="2">
<dx:DXTabItem x:Name="tabAttributes" Header="License Attributes" >
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="30" />
<RowDefinition Height="30" />
<RowDefinition Height="30" />
<RowDefinition Height="30"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="120" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<TextBlock Text="Activation Mode:" Style="{StaticResource TabMargin}" />
<dx:DropDownButton Grid.Row="0" Grid.Column="1" Width="100" HorizontalAlignment="Left" Style="{StaticResource TabMargin}" ButtonKind="Repeat" />
<TextBlock Text="Grace Period:" Style="{StaticResource TabMargin}" Grid.Row="1"/>
<StackPanel Grid.Row="1" Grid.Column="1" Orientation="Horizontal">
<dxe:SpinEdit Width="80" Style="{StaticResource TabMargin}" MinValue="0" MaxValue="100" IsReadOnly="True" Value="10" Mask="n0"/>
<TextBlock Text="Days" Style="{StaticResource TabMargin}" />
</StackPanel>
<dxe:CheckEdit Grid.Row="2" Content="Expiration Date" IsChecked="False" />
<dxe:DateNavigator Grid.Row="2" Grid.Column="1" Width="185" HorizontalAlignment="Left" Style="{StaticResource TabMargin}" />
<TextBlock Text="Max Computers:" Grid.Row="3" Style="{StaticResource TabMargin}"/>
<dxe:SpinEdit Grid.Row="4" Grid.Column="1" HorizontalAlignment="Left" Width="80" Margin="2.5,2.5,2.5,1" MinValue="0" MaxValue="100" IsReadOnly="True" Value="10" Mask="n0"/>
</Grid>
</dx:DXTabItem>
<dx:DXTabItem Header="Product Features" x:Name="tabProductFeatures" Visibility="Visible">
<StackPanel Orientation="Vertical" >
<dxe:CheckEdit Content="Standard" Name="chkStandard" IsReadOnly="True" Style="{StaticResource ckkStyle}" />
<dxe:CheckEdit Content="Admin Mode" Name="chkAdminMode" IsReadOnly="True" Style="{StaticResource ckkStyle}" />
<dxe:CheckEdit Content="Batch Mode" Name="chkBatchMode" IsReadOnly="True" Style="{StaticResource ckkStyle}" />
<dxe:CheckEdit Content="Custom Data Series" Name="chkCustomDataSeries" IsReadOnly="True" Style="{StaticResource ckkStyle}" />
<dxe:CheckEdit Content="Local DataBase" Name="LocalDataBase" IsReadOnly="True" IsChecked="True" Style="{StaticResource ckkStyle}"/>
<dxe:CheckEdit Content="Cloud Data Base" Name="CloudDataBase" Style="{StaticResource ckkStyle}" />
</StackPanel>
</dx:DXTabItem>
<dx:DXTabItem Name="tabComputers" Header="Computers">
<dxg:GridControl Name="grdComputers">
</dxg:GridControl>
</dx:DXTabItem>
<dx:DXTabItem Name="tabMain_Schedule" Header="Maint. Schedule">
<dxg:GridControl>
</dxg:GridControl>
</dx:DXTabItem>
<dx:DXTabItem x:Name="tabFeaturePB" Header="Product Features">
<StackPanel Orientation="Vertical">
<dxe:CheckEdit Content="pb" Name="chkpb" IsReadOnly="True" Style="{StaticResource ckkStyle}" />
<dxe:CheckEdit Content="pb2" Name="chkpb2" IsReadOnly="True" Style="{StaticResource ckkStyle}" />
</StackPanel>
</dx:DXTabItem>
</dx:DXTabControl>
</Grid>
The DataContext class of the mainwindows is this
public class CustomerLicenses
{
private Customer _Customer;
private LicenseList _Licenses;
private License _SelectedLicense;
//private Guid _SelectedSerial;
//public delegate void SelectLicenseEventArg(String SerialNum);
//public event SelectLicenseEventArg SelectLicense;
public CustomerLicenses(Customer Customer)
{
_Customer = Customer;
}
public CustomerLicenses(Customer customer, LicenseList licenses)
{
_Customer = customer;
_Licenses = licenses;
}
public CustomerLicenses()
{
_Customer = new Customer();
_Licenses = new LicenseList();
}
[DataMember]
public Customer Customer
{
get { return _Customer; }
set
{
if (_Customer != value)
{
this._Customer = value;
this.NotifyPropertyChanged("Customer");
}
}
}
[DataMember]
public LicenseList Licenses
{
get { return _Licenses;}
set
{
if (_Licenses != value)
{
this._Licenses = value;
this.NotifyPropertyChanged("Licenses");
}
}
}
private DataTable GetLicensesTable()
{
var dt = new DataTable();
dt.Columns.AddRange(new DataColumn []{
new DataColumn("SerialNumber",typeof(string)),
new DataColumn("Product",typeof(string)),
new DataColumn("Status",typeof(string)),
new DataColumn("ActivationMode",typeof(string)),
new DataColumn("MaxComputers", typeof(int)),
new DataColumn("NumActive",typeof(int)),
new DataColumn("Description",typeof(string)),
new DataColumn("License",typeof(object))
});
_Licenses.ForEach((x) => {
var rw = dt.NewRow();
rw["SerialNumber"] = x.SerialNumber;
rw["Product"] = x.Product.Name;
rw["Status"] = x.Status;
rw["ActivationMode"] = Enum.GetName(typeof(ActivationModeEnum), x.ActivationMode); //x.ActivationMode;
rw["MaxComputers"] = x.MaxComputers;
rw["NumActive"] = Activated(x.Product.ProductId);
rw["Description"] = x.Description;
rw["License"] = x;
dt.Rows.Add(rw);
});
return dt;
}
public DataTable LicensesTable{
get { return GetLicensesTable(); }
}
[DataMember]
public License SelectedLicense {
get { return _SelectedLicense;}
set {
this.NotifyPropertyChanged("SelectedLicense");
_SelectedLicense = value;
}
}
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(string propName)
{
if (this.PropertyChanged != null)
this.PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propName));
}
}
In this part im populating the textblock with the serial, and is ok it shows when i start the app `cause takes the first license but if i select another license the text does not change.
TextBlock Text="{Binding Path=DataContext.SelectedLicense.SerialNumber, UpdateSourceTrigger=PropertyChanged, RelativeSource={RelativeSource AncestorType=Window}}" x:Name="txtSerialNum" Grid.Column="1" Grid.Row="1" Style="{StaticResource ResourceKey=SmalllMarginTextBlock}"
This is how i assaing the value when the grid chanege selection
private void GridRowSelected (object sender, SelectedItemChangedEventArgs e)
{
try
{
var Record = (DataRowView)grdLicenses.grdLicences.SelectedItem;
var SelectedLicense = (License)Record["License"];
_CustomerLicense.SelectedLicense = SelectedLicense;
//Customer_Detail.DataContext = SelectedCustomer;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
How can i update the child when the item is selected in the grid.
Regards
sTrenat, as you said i checked the class and i was wrong implementing the propertyfotify
i changed to this
[DataContract]
public class CustomerLicenses: System.ComponentModel.INotifyPropertyChanged
{
public void NotifyPropertyChanged(string propName)
{
System.ComponentModel.PropertyChangedEventHandler handler = PropertyChanged;
if (this.PropertyChanged != null)
this.PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propName));
}
}
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
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).