1

I'm trying to handle the MaxLength of a TextBox via Binding. I'm using a Helper Class called 'MaxLengthConverter' (see here http://mariabrinas.com/?p=89). The TextBox looks currently like this:

<TextBox MaxLength="{Binding TestValue, Mode=TwoWay, Converter={StaticResource MaxLengthConverter}, ConverterParameter='7'}" Text="{Binding TestValue, Mode=TwoWay}" InputScope="Number" />

And the MaxLengthValueConvert looks like this:

public class MaxLengthConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)

        if (value.ToString().Contains('.'))
        {
            string[] len = value.ToString().Split('.');
            parameter = len[0].Length + 2;
        }


    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return parameter;
    }
}

The parameter is the length of the value. In this example it's 7. The max. length of the TextBox will be 7, but if the user types a '.' (decimal point), the maxlength will be the current length + 2, so he can only write 23.45 and not 23.456. The problem is that the ValueConvert will only be called when I'm leaving the TextBox (LostFocus). How can I call the ValueConverter every time the user types something in (KeyDown) ?

Rudi
  • 926
  • 2
  • 19
  • 38

1 Answers1

0

Define an explicit UpdateSourceTrigger as PropertyChanged since textbox default is LostFocus

Eg:

  <TextBox>
  <TextBox.Text>
    <Binding Source="{StaticResource myDataSource}" Path="Name"
             UpdateSourceTrigger="PropertyChanged"/>
  </TextBox.Text>
</TextBox>
S.N
  • 4,910
  • 5
  • 31
  • 51
  • XAML can't find after . Since I'm coding a windows phone 8 app, I also guess there's no PropertyChanged for UpdateSourceTrigger. The only options for UpdateSourceTrigger is 'Default' and 'Explicit'. – Rudi May 24 '13 at 10:41
  • 1
    All right. Can you check this http://stackoverflow.com/questions/12692885/updatesourcetrigger-propertychanged-equivalent-for-a-textbox-in-winrt-xaml – S.N May 24 '13 at 10:46
  • Thanks. gonna have a look at it. – Rudi May 24 '13 at 10:52