【问题标题】:enable a button when user starts typing wpf当用户开始输入 wpf 时启用按钮
【发布时间】:2013-07-01 22:53:26
【问题描述】:

我有 3 个文本框和一个搜索按钮。

<TextBox Grid.Row="1" Grid.ColumnSpan="2" VerticalAlignment="Center" HorizontalAlignment="Stretch" Text="{Binding Id, Mode=TwoWay}"/>
<TextBox Grid.Row="3" Grid.ColumnSpan="2" VerticalAlignment="Center" HorizontalAlignment="Stretch" Text="{Binding Name, Mode=TwoWay}"/>
<TextBox Grid.Row="5" Grid.ColumnSpan="2" VerticalAlignment="Center" HorizontalAlignment="Stretch" Text="{Binding Phone, Mode=TwoWay}"/>
<Button Grid.Row="8" Grid.ColumnSpan="2" Content="Search" Command="{Binding SearchPerson}" />

我已经实现了用户在任何文本框中输入内容,然后离开文本框,此时搜索按钮被启用的逻辑。

但是,我希望当用户在任何文本框中“开始输入”(字符串不应为空或空格)时启用搜索按钮。

我如何实现这个??

在此先感谢...

【问题讨论】:

  • 只需将UpdateSourceTrigger=PropertyChanged 添加到每个TextBox.Text 的绑定中。如果您的逻辑当前保持正常,那么一旦您开始输入就可以了
  • 嘿 viv...既然你是第一个发布的,你想发表这个评论作为答案...以便我接受吗?
  • 当然,完成。添加了指向 MSDN 文档的链接,该链接解释了此行为以及您可能想要检查的行为

标签: c# .net wpf data-binding wpf-4.0


【解决方案1】:

如果您希望在键入时更新源代码,则需要将绑定上的 UpdateSourceTrigger property 设置为 PropertyChanged

所以将你的绑定更改为:

Text="{Binding Id, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
Text="{Binding Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
Text="{Binding Phone, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"

【讨论】:

    【解决方案2】:

    好的,只是将我的评论转换为答案。

    MSDN Docs中所述

    TextBox.Text 属性的默认 UpdateSourceTrigger 值为 LostFocus。

    因此,要使其“尽快”,您只需在 TextBox.Text 绑定上显式切换 UpdateSourceTrigger=PropertyChanged

    类似的东西(在每个TextBox):

    Text="{Binding Id, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
    

    【讨论】:

      【解决方案3】:

      为什么不使用简单的 TextBox->OnTextChange 事件:

      button1.IsEnabled = !string.IsNullOrWhiteSpace((sender as TextBox).Text);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-08-05
        • 2011-02-02
        • 2013-09-10
        • 1970-01-01
        • 2012-04-25
        • 2010-10-23
        • 1970-01-01
        相关资源
        最近更新 更多