【问题标题】:Return Focus to WPF Element when contents fail validation内容验证失败时将焦点返回到 WPF 元素
【发布时间】:2018-04-06 05:03:04
【问题描述】:

当文本框失去焦点时,我正在验证输入的数据。 当我的验证规则将 TextBox 的内容识别为无效时,我想自动将焦点返回到 TextBox。 我的理由是,如果用户必须重新输入有效数据,我可以通过为他们预先定位光标来为他节省一次击键。

我将 TextBox 的名称传递给验证类,就像这样...

<TextBox x:Name="addAnInteger">
<Binding.ValidationRules>                                            
     <local:ValidateInteger32 TextBoxName="addAnInteger"/>                                                     
</Binding.ValidationRules>
</TextBox>

在验证类 (ValidateInteger32) 我有:

public string TextBoxName { get; set; }

属性 TextBoxName 接收并存储我想要将焦点重置到的 TextBox 的名称。

如何仅使用属性 TextBoxName 的名称从 ValidateInteger32 验证类内部将焦点设置回“addAnInteger”文本框?我在想类似......

[Commands that expose the contents of TextBoxName].Focus();

我不想在验证类中使用单个文本框的名称,因为我希望该类是通用的。

感谢任何建议。

【问题讨论】:

    标签: c# wpf xaml data-binding


    【解决方案1】:

    您可以使用Validation.Error 事件。你会在那里获得实例。

    看看这个:Validation.error event in event command

    【讨论】:

    • 你能告诉我怎么做吗?
    【解决方案2】:

    ValidationRule 只返回一个ValidationResult。它对视图中的TextBox 一无所知。

    控件/视图本身有责任对验证结果进行操作。例如,您可以像这样处理Validation.Error 事件:

    private void addAnInteger_Error(object sender, ValidationErrorEventArgs e)
    {
        TextBox textBox = (TextBox)sender;
        textBox.Dispatcher.BeginInvoke(new Action(() => { Keyboard.Focus(textBox); }), System.Windows.Threading.DispatcherPriority.Background);
    }
    

    XAML:

    <TextBox x:Name="addAnInteger" Margin="10" Validation.Error="addAnInteger_Error">
        <TextBox.Text>
            <Binding Path="Text" NotifyOnValidationError="True">
                <Binding.ValidationRules>
                    <local:ValidateInteger32 />
                </Binding.ValidationRules>
            </Binding>
        </TextBox.Text>
    </TextBox>
    

    或者您将不得不以某种方式将对实际TextBox 的引用绑定到ValidationRule。有关此问题的更多信息,请参阅我的回答:

    How to bind values from xaml to validation rule?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-05
      • 1970-01-01
      相关资源
      最近更新 更多