Handling MaxLength via Binding

倾然丶 夕夏残阳落幕 提交于 2019-12-11 06:19:58

问题


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) ?


回答1:


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>


来源:https://stackoverflow.com/questions/16732782/handling-maxlength-via-binding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!