wpf maskedTextBox Databindings - wpf

I am using the following MaskedTextBox http://wpftoolkit.codeplex.com/wikipage?title=MaskedTextBox in a person project for my own use. This is a simple example because i am trying to use this on a much bigger program but I am using this program to test this control.
STEPS:
1. Create a wpf application
2. Added a Linq to SQL Class called Prescriptions and added a table called info
{ID | Name | Phone}
The markup for the form is listed below:
<Window x:Class="MaskedTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
Title="MainWindow" Height="300" Width="300"
Loaded="Window_Loaded">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="200"/>
</Grid.ColumnDefinitions>
<Label Name="nameLabel" Margin="2" Target="{Binding ElementName=nameTxt}">_Full Name</Label>
<TextBox Name="nameTxt" Grid.Column="1" Margin="2" Text="{Binding Name}"/>
<Label Name="phoneLabel" Margin="2" Grid.Row="1" Grid.Column="0" Target="{Binding ElementName=phoneTxt}">_Phone Numnber</Label>
<xctk:MaskedTextBox Name="phoneTxt" Margin="2" Grid.Row="1" Grid.Column="1" Text="{Binding Phone}" Mask="(000) 000-0000" />
</Grid>
Code Behind File:
public partial class MainWindow : Window
{
private PrescriptionDataContext pdc = new PrescriptionDataContext();
private List<info> users = new List<info>();
private info U = new info { Id = 1, Name = "Matthew Brown", Phone = "5128289081" };
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
var q = pdc.getUser();
foreach (info I in q)
{
users.Add(I);
}
// DOES NOT WORK
this.DataContext = users;
// WORKS
// this.DataContext = U;
}
}
When this loads, you will see that the name field has been binded correctly but the phone control shows only the mask not the underlying data from the table. If I explicity create the class and then bind it like i did above it works.
Ideas??

Related

How to bind wpf UserControl?

I am having a problem to binding viewmodel to my created usercontrol. The viewmodel doesn't reflect the value changes.
UpDown.xaml (Usercontrol xaml part)
btnUp and btnDown are used to change the text of txtNum. I don't know whether it is right?
<Grid DataContext="{Binding ElementName=btnDownRoot}">
<Grid.RowDefinitions>
<RowDefinition Height="0*"/>
<RowDefinition/>
<RowDefinition Height="0*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0*"/>
<ColumnDefinition Width="78*"/>
<ColumnDefinition Width="104*"/>
<ColumnDefinition Width="77*"/>
<ColumnDefinition Width="0*"/>
</Grid.ColumnDefinitions>
<TextBox Name="txtNum" Text="{Binding ElementName=btnDownRoot, Path=NumValue}" FontSize="20" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" BorderBrush="White" Grid.Column="2" Grid.RowSpan="2"/>
<Button Name="btnUp" Style="{StaticResource ResourceKey=btnUp}" Click="btnUp_Click" Grid.Column="3" Grid.RowSpan="2"/>
<Button Name="btnDown" Style="{StaticResource ResourceKey=btnDown}" Click="btnDown_Click" Grid.RowSpan="2" Grid.ColumnSpan="2"/>
</Grid>
UpDown.xaml.cs (Usercontrol codepart)
public string NumValue
{
get
{
return GetValue(NumValueProperty).ToString();
}
set
{
SetValue(NumValueProperty, value);
}
}
public static readonly DependencyProperty NumValueProperty =
DependencyProperty.Register("NumValue", typeof(string), typeof(UpDown),
new PropertyMetadata("1", new PropertyChangedCallback(OnNumChanged)));
private static void OnNumChanged(DependencyObject d,DependencyPropertyChangedEventArgs e)
{
var instannce = d.ToString();
}
In the MainWindow,I am going to bind the MainViewModel to the UserControl
MainViewModel.cs
public class MainViewModel: BaseViewModel
{
private string _myValue;
public string MyValue
{
get { return _myValue; }
set
{
_myValue = value;
OnPropertyChanged("MyValue");
}
}
}
MainWindow.xaml
<Window.DataContext>
<local:MainViewModel/>
</Window.DataContext>
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<local:UpDown Grid.Row="0" NumValue="{Binding MyValue}" x:Name="udGuestNum" Width="220" Margin="0 20"/>
<Button Name="btnOK" Grid.Row="1" Content="OK" Click="btnOK_Click"/>
</Grid>
The NumValue Binding is OneWay by default. Either explicitly set it to TwoWay
NumValue="{Binding MyValue, Mode=TwoWay}"
or make TwoWay the default:
public static readonly DependencyProperty NumValueProperty =
DependencyProperty.Register(
"NumValue", typeof(string), typeof(UpDown),
new FrameworkPropertyMetadata(
"1", FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnNumChanged));
numeric up/down control have already been developed...don't waste your time, you can even grab the code > https://github.com/xceedsoftware/wpftoolkit

IsAvailable always false with Kinect Studio on IsAvailableChanged

Environ: Kinect 2.0 SDK, Kinect Studio, Windows 10, WPF
e.IsAvailailable is always returning false when I'm driving my programming via the Kinect Studio ( https://msdn.microsoft.com/en-us/library/microsoft.kinect.kinectsensor.isavailable.aspx ). I would think it would return true if it were receiving data. Note the BodyReader frames are arriving even though the sensor started unavailable and never tripped the IsAvailableChanged handler. Note the BodyBasics-WPF SDK 2.0 sample behaves the same way.
A number of code samples stop if they get e.IsAvailable=false. Probably a bad move if you are using Kinect Studio and playback.
Bug? Feature? Lack of documentation?
Kinect against Kinect Studio - IsAvailable = false
Kinect against Physical Kinect - IsAvailable = true
Code and XAML below...
public partial class MainWindow : Window
{
private KinectSensor m_kinectSensor = null;
private BodyFrameReader m_bodyReader;
private Body[] m_bodies = null;
public MainWindow()
{
this.m_kinectSensor = KinectSensor.GetDefault();
this.m_kinectSensor.IsAvailableChanged += KinectSensor_IsAvailableChanged;
this.m_kinectSensor.Open();
// hook the body stuff
this.m_bodyReader = m_kinectSensor.BodyFrameSource.OpenReader();
this.m_bodyReader.FrameArrived += BodyReader_FrameArrived;
InitializeComponent();
Msg("MainWindow c'tor completed");
}
private void BodyReader_FrameArrived(object sender, BodyFrameArrivedEventArgs e)
{
Msg(String.Format("BodyReader_FrameArrived: {0}" , e.FrameReference.RelativeTime.ToString()));
}
private void KinectSensor_IsAvailableChanged(object sender, IsAvailableChangedEventArgs e)
{
System.Diagnostics.Debug.WriteLine( "KinectSensor_IsAvailableChanged: e.IsAvailable=" + e.IsAvailable.ToString() );
TextBlock_StatusBar.Text = "KINECT SENSOR STATUS: " + e.IsAvailable.ToString();
}
private void Msg ( string s )
{
if (s.Length <= 0) s = "ready";
TextBlock_Msg.Text = s;
}
}
}
XAML
<Window x:Class="FaceNSkinWPF.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:FaceNSkinWPF"
mc:Ignorable="d"
Title="MainWindow"
Height="600" Width="800"
>
<Grid Margin="10,10,10,10">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<StackPanel Grid.Row="0" Orientation="Horizontal" HorizontalAlignment="Center">
<Button Content="ButtonOne" Width="150" Height="30" Margin="10"/>
<Button Content="ButtonOne" Width="150" Height="30" Margin="10"/>
<Button Content="ButtonOne" Width="150" Height="30" Margin="10"/>
</StackPanel>
<Viewbox Grid.Row="1" HorizontalAlignment="Center">
<Image Source="{Binding ImageSource}" Stretch="UniformToFill" />
</Viewbox>
<StackPanel Grid.Row="2" Orientation="Vertical">
<TextBlock x:Name="TextBlock_StatusBar" Height="20" Foreground="Black" FontWeight="Bold" Text="KINECT SENSOR STATUS: unknown"/>
<TextBlock x:Name="TextBlock_Msg" Height="20" Foreground="Blue" FontWeight="Bold" Text="ready"/>
</StackPanel>
</Grid>

Accessing DataContext properties in View

I'm hoping someone can give me a kick in the right direction, I'm currently learning WPF and MVVM - let's say its not been plain sailing. Basically I'm trying to access the properties of DataContext and bind them to a property in my view. I'll be completely honest, I've got myself in a bit of a tangle.
When the user clicks the button in question it fires the code below.
private void OnReceiptClick(object sender, RoutedEventArgs e)
{
var dialogBox = new DisplayReceiptView(((CheckMemberViewModel) this.DataContext).ReceiptViewModel);
dialogBox.ShowDialog();
}
My CheckMemberViewModel currently holds the 'Person' property I'm after, and at this stage DataContext is populated as expected.
The code behind my DisplayReceiptView looks like the following:
public DisplayReceiptView(ReceiptViewModel context) : this()
{
this.DataContext = context;
}
Once again everything seems correct, and finally in my XAML I have
<Grid DataContext="{Binding Path=Person}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="10"/>
<ColumnDefinition Width="150"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="10" />
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Label Grid.Column="1" Grid.Row="1">Name:</Label>
<TextBox Grid.Column="2" Grid.Row="1" Text="{Binding Path=Person.Forename}"></TextBox>
</Grid>
Unfortunately no matter what I've done, and I think where I'm up to at the moment is the closest I've been, the data doesn't seem to bind. Below is my ViewModel code for the properties
private Person _person;
public Person Person
{
get { return _person; }
set
{
if (value != _person)
{
_person = value;
OnPropertyChanged("Person");
}
}
}
Any help is greatly appreciated.
<TextBox Grid.Column="2" Grid.Row="1" Text="{Binding Path=Person.Forename}"></TextBox>
This is wrong as you are already bound to Person
<TextBox Grid.Column="2" Grid.Row="1" Text="{Binding Forename}"></TextBox>
Is all you need
<TextBox Grid.Column="2" Grid.Row="1" Text="{Binding Forename, Mode=TwoWay}"></TextBox>
Will save changes to the source and retrieve changes, but of course you will need to save context changes to make them permanent

It is possible to do 'simple' binding with a UserControl?

I have a user control in which I have some textblocks. I want to include this usercontrol into a listBox (or listview in case it causes any problems).
When I check the output windows, I see no binding exception, but I don't see anything in the textblock either.
Is there anyway to make this work ?
Thanks :
Here is the listBox I use for now :
<ListBox AllowDrop="True" Grid.Row="1"
Style="{StaticResource BaseListBox}" x:Name="LstEquipeDefaut">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<my:ucEquipe x:Name="ucEquipe" Grid.Row="1" Margin="5,0,5,2"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Here is the Usercontrol :
<UserControl x:Class="ucEquipe"
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:telerik="http://schemas.telerik.com/2008/xaml/presentation"
mc:Ignorable="d"
d:DesignHeight="350" d:DesignWidth="180" MinWidth="180" >
<Border Style="{StaticResource UControlBorder}">
<Grid x:Name="LayoutRoot">
<Grid.RowDefinitions>
<RowDefinition Height="32" />
<RowDefinition Height="25" />
<RowDefinition Height="35" />
<RowDefinition Height="100" />
<RowDefinition Height="35" />
<RowDefinition Height="100" />
</Grid.RowDefinitions>
<TextBox AllowDrop="True" x:Name="TxtChiefEquipe"
Style="{StaticResource BaseTextBox}"
Text="{Binding Mode=OneWay,Path=chefEquipe.NomComplet}"
Grid.Row="1" />
</Grid>
</Border>
Here is the objets I use :
Public Class Equipe
Public Property ID As Long = 0
Public Property Couleur As String = ""
Public Property Semaine As New Date(1900, 1, 1)
Public Property chefEquipe As Employe = Nothing
Public Property ListEquipeEmploye As New List(Of EquipeEmploye)
Public Property ListEquipeEquipement As New List(Of EquipeEquipement)
End Class
The objet Employe have a property called NomComplet. For now I manually added new objects in the listbox for testing.
Your Equipe class needs to implement INotifyPropertyChanged
private Employe _chefEquipe;
public Employe ChefEquipe
{
get { retun _chefEquipe; }
set
{
_chefEquipe = value;
NotifyPropertyChanged("ChefEquipe");
}
}
Sorry about the C#, I don't remember the VB syntax anymore =)

Dataform range validation not working

I'm trying to raise validation errors:
1. when the user enter a US MSRP that is not a number, silverlight displays an error when leaving the field
2. However if in the same field I put a negative number, no error is displayed even though there is an explicit range specified
What do I need to change?
Also, as a bonus question, what am I supposed to use in the XAML to read the value Display(Name = "My Name is US MSRP:" rather than explicitly specifying something else
public class CalculatorParameters : INotifyPropertyChanged
{
private double _usMsrp;
public CalculatorParameters()
{
}
[Display(Name = "My Name is US MSRP:",
Description = "The residual value is based on the US MSRP, even with Euro-Delivery")]
[Range(0, 150000, ErrorMessage = "US MSRP must be a positive amount under $150,000")]
public double UsMsrp
{
get { return _usMsrp; }
set
{
_usMsrp = value;
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("UsMsrp"));
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
}
And here is the XAML
<UserControl x:Class="Silverlight.ConfigEnhanced.UcFinance"
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:my="clr-namespace:Silverlight.ConfigEnhanced"
xmlns:df="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data.DataForm.Toolkit"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="650" d:DesignWidth="500" >
<UserControl.Resources>
<my:CalculatorParameters x:Key="descriptor"/>
</UserControl.Resources>
<df:DataForm x:Name="df1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" CurrentItem="{StaticResource descriptor}" CommandButtonsVisibility="None" AutoGenerateFields="False" >
<df:DataForm.EditTemplate>
<DataTemplate>
<Grid x:Name="LayoutRoot" Background="White">
<Grid.RowDefinitions>
<RowDefinition Height="160"></RowDefinition>
<RowDefinition Height="20"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="270"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"></ColumnDefinition>
<ColumnDefinition Width="*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<StackPanel Grid.Row="2" Grid.Column="0">
<TextBlock Text="Leasing" HorizontalAlignment="Center" VerticalAlignment="Center" FontWeight="Bold" Margin="0,0,0,15" />
<df:DataField Label="Term in Months">
<TextBox Name="txtBoxLeaseTermInMonths" Text="{Binding LeaseTermInMonths, Mode=TwoWay}" GotFocus="RecomputeLease"/>
</df:DataField>
<df:DataField Label="Down Payment">
<TextBox Name="txtBoxLeaseDownPayment" Text="{Binding LeaseDownPayment, Mode=TwoWay}" GotFocus="RecomputeLease"/>
</df:DataField>
<df:DataField Label="Money Factor">
<TextBox Name="txtBoxLeaseMoneyFactor" Text="{Binding MoneyFactor, Mode=TwoWay}" GotFocus="RecomputeLease"/>
</df:DataField>
<df:DataField Label="US MSRP">
<TextBox Name="txtBoxLeaseUsMsrp" Text="{Binding UsMsrp, Mode=TwoWay}" GotFocus="RecomputeLease"/>
</df:DataField>
</StackPanel>
</Grid>
</DataTemplate>
</df:DataForm.EditTemplate>
</df:DataForm>
</UserControl>
http://betaforums.silverlight.net/forums/p/113795/257670.aspx

Resources