You can't directly bind to a decimal
from a TextBox
without handling a data conversion when you're doing TwoWay
binding. The TextBox
Text
property is of type string. A simple converter like this would be necessary (using IValueConverter
(reference)):
public class DecimalConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, string language)
{
return value.ToString();
}
public object ConvertBack(object value, Type targetType,
object parameter, string language)
{
decimal d;
if (value is string)
{
if (decimal.TryParse((string)value, out d))
{
return d;
}
}
return 0.0;
}
}
And as a Resource
:
<local:DecimalConverter x:Key="decimalConverter" />
Then, in use:
<TextBox Grid.Row="1" Grid.Column="0"
Text="{Binding One, Mode=TwoWay,
Converter={StaticResource decimalConverter}}"
InputScope="Number" Margin="5,0" />
The InputScope
just is a suggestion to Windows as to what keyboard should be displayed by default when the field gets focus. It does not prevent unwanted keys (or alphabetic characters).
Also, be sure to call PropChanged
with the name of the property being changed. They're wrong in your code.
One thing you should always use when bindings aren't working as expected in a XAML/WPF application is to check the Visual Studio Output
window for errors. You would see something like this for example:
Error: Cannot save value from target back to source. BindingExpression: Path='Two' DataItem='Win8CSharpTest.NeckData, Win8CSharpTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'; target element is 'Windows.UI.Xaml.Controls.TextBox' (Name='null'); target property is 'Text' (type 'String').