【问题标题】:Handling MaxLength via Binding通过绑定处理 MaxLength
【发布时间】:2013-05-24 10:22:47
【问题描述】:

我正在尝试通过 Binding 处理 TextBox 的 MaxLength。我正在使用一个名为“MaxLengthConverter”的 Helper 类(参见此处http://mariabrinas.com/?p=89)。 TextBox 目前看起来像这样:

<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。 问题是 ValueConvert 只会在我离开 TextBox (LostFocus) 时被调用。每次用户在 (KeyDown) 中输入内容时如何调用 ValueConverter?

【问题讨论】:

    标签: c# data-binding microsoft-metro windows-phone-8 ivalueconverter


    【解决方案1】:

    将明确的UpdateSourceTrigger 定义为PropertyChanged,因为文本框默认为LostFocus

    例如:

      <TextBox>
      <TextBox.Text>
        <Binding Source="{StaticResource myDataSource}" Path="Name"
                 UpdateSourceTrigger="PropertyChanged"/>
      </TextBox.Text>
    </TextBox>
    

    【讨论】:

    • XAML 在 之后找不到 。由于我正在编写 Windows Phone 8 应用程序,我也猜想 UpdateSourceTrigger 没有 PropertyChanged。 UpdateSourceTrigger 的唯一选项是“默认”和“显式”。
    • 好的。你能检查一下这个stackoverflow.com/questions/12692885/…
    • 谢谢。去看看吧。
    猜你喜欢
    • 1970-01-01
    • 2017-07-27
    • 2016-03-23
    • 2017-04-27
    • 2015-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多