通过绑定处理MaxLength [英] Handling MaxLength via Binding
问题描述
< TextBox MaxLength ={Binding TestValue,Mode = TwoWay,Converter = {StaticResource MaxLengthConverter },ConverterParameter ='7'}Text ={Binding TestValue,Mode = TwoWay}InputScope =Number/>
MaxLengthValueConvert如下所示:
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;
}
}
参数是值的长度。在这个例子中,它是7.最大。 TextBox的长度将为7,但是如果用户键入'。'(小数点),则maxlength将为当前长度+ 2,因此只能写入23.45而不是23.456。
问题是当我离开TextBox(LostFocus)时,ValueConvert将被调用。每当用户在(KeyDown)中键入一些东西时,如何调用ValueConverter?
定义一个显式的 UpdateSourceTrigger
as PropertyChanged
由于文本框默认为LostFocus
例如:
< TextBox>
< TextBox.Text>
< Binding Source ={StaticResource myDataSource}Path =Name
UpdateSourceTrigger =PropertyChanged/>
< /TextBox.Text>
< / TextBox>
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) ?
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>
这篇关于通过绑定处理MaxLength的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!